excel - 从url下载图片并保存到以单元格命名的文件夹中

标签 excel vba

我有一个包含文件夹名称、图像名称和 URL 的工作表。我想将每个图像下载到特定文件夹,以便结果如下所示:

Folder Name   Image Name     URL
-----------   ------------   -----------------------------------
folder1      image1         http://www.example.com/example1.jpg
folder2      image2         http://www.example.com/example2.jpg
folder3      image3         http://www.example.com/example3.jpg
folder4      image4         http://www.example.com/example4.jpg
folder5      image5         http://www.example.com/example5.jpg

C:\images\folder1\image1.jpg
C:\images\folder2\image2.jpg
C:\images\folder3\image3.jpg
C:\images\folder4\image4.jpg
C:\images\folder5\image5.jpg

我找到了这个 VBA 代码,它的工作方式就像一个魅力,但我不知道如何添加一个方法来创建文件夹(如果文件夹不存在):

Option Explicit

Private Declare Function URLDownloadToFile Lib "urlmon" _
Alias "URLDownloadToFileA" (ByVal pCaller As Long, _
ByVal szURL As String, ByVal szFileName As String, _
ByVal dwReserved As Long, ByVal lpfnCB As Long) As Long

Dim Ret As Long

'~~> This is where the images will be saved. Change as applicable
Const FolderName As String = "C:\Temp\"

Sub Sample()
    Dim ws As Worksheet
    Dim LastRow As Long, i As Long
    Dim strPath As String

    '~~> Name of the sheet which has the list
    Set ws = Sheets("Sheet1")

    LastRow = ws.Range("A" & Rows.Count).End(xlUp).Row

    For i = 2 To LastRow '<~~ 2 because row 1 has headers
        strPath = FolderName & ws.Range("A" & i).Value & ".jpg"

        Ret = URLDownloadToFile(0, ws.Range("B" & i).Value, strPath, 0, 0)

        If Ret = 0 Then
            ws.Range("C" & i).Value = "File successfully downloaded"
        Else
            ws.Range("C" & i).Value = "Unable to download the file"
        End If
    Next i
End Sub

最佳答案

以下将确定文件夹是否存在,如果不存在,则创建它:

If Len(Dir(FolderName, vbDirectory)) = 0 Then
   MkDir FolderName
End If

修改自 here

对于更高级的内容,我建议使用 FileSystemObject 类。

关于excel - 从url下载图片并保存到以单元格命名的文件夹中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23742636/

相关文章:

excel - 在调试 VBA 代码时,我在保存“第 8 行需要对象”时遇到错误

javascript - Javascript 中的标准偏差,适用于 MS Excel API

vb.net - Range 类的 AutoFilter 方法在 VB.NET 中失败

php - 在php中插入excel上传查询

sql - VBA 代码 - 将文本文件导入 Access 表 - 有条件

vba - 关闭时 Access 崩溃

vba - Excel VBA 保存带有日期的自动筛选设置

excel - 当使用 vba 单击搜索按钮时,网页看不到在搜索框中输入的文本

excel - 为什么我在 VBA 循环中遇到 Dir 错误?

vba - 为什么返回 Range 的 Excel/VBA 用户定义的默认属性的行为与 Range 不同?