自动下载图像列表并命名

时间:2013-09-15 22:54:54

标签: windows excel vba download

我有一张xls / csv图片列表:

Name        image url
test.jpg    http://test.com/232dd.jpg
test2.jpg   http://test.com/2390j.jpg

我有大约200个......有没有办法下载列表并将它们命名为xls文件中标识的?

这是我的Excel VBA:

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

Private Sub download_pics()
  Dim rng As Range
  Dim cell As Variant

  Set rng = Range("A1:B10")
  For Each cell In rng
    ' Download the file.
    URLDownloadToFile 0, cell(rng, 2).Value, "C:\" & cell(rng, 1).Value, 0, 0
  Next
End Sub

使用URLDownloadToFile

遇到类型不匹配错误

1 个答案:

答案 0 :(得分:0)

确定类型不匹配与您的迭代有关。您需要使用rng语句指定迭代For each cell in rng的方式,例如:

For each cell in rng.Rows

否则,它将该语句视为For each cell in rng.Cells并且会引发不匹配错误。

我对代码进行了一些修改(基于Sid的回答here),因此它会检查以确保文件成功下载,但大多数情况下你发现的是正确的,你只需稍微改变一下即可。

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

Private Sub download_pics()
  Dim rng As Range
  Dim myRow As Range
  Dim imgName As String
  Dim fileLocation As String
  Dim Ret As Long 'return value from the URLDownloadToFile function
  Set rng = Range("A1:B10")
  For Each myRow In rng.Rows
    With myRow
        imgName = .Columns(2).Value
        fileLocation = "C:\" & .Columns(1).Value
        With .Columns(1).Offset(, 2)
            If URLDownloadToFile(0, imgName, fileLocation, 0, 0) = 0 Then
                .Value = "downloaded successfully"
            Else:
                .Value = "download failed!"
            End If
        End With
    End With
  Next
End Sub