URLDownloadToFile生成编译错误:子或函数未定义

时间:2019-06-20 17:17:57

标签: excel vba download

我正在尝试将图像从URL下载到文件夹中。我从this question的成功答案中获得了以下代码。

Sub DownloadLinks()
    Dim ws As Worksheet
    Dim LastRow As Long, i As Long
    Dim strPath As String, strURL As String
    Dim c As Range

    Set ws = Sheets("Sheet1")

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

    For i = 2 To LastRow

        Set c = ws.Range("BP" & i)
        If c.Hyperlinks.Count>0 Then
            strPath = FolderName & c.Value & ".jpg"
            strURL = c.Hyperlinks(1).Address

            Ret = URLDownloadToFile(0, strURL, strPath, 0, 0)

            ws.Range("CA" & i).Value = IIf(Ret = 0, _
                                    "File successfully downloaded", _
                                    "Unable to download the file")
        Else
            ws.Range("CA" & i).Value = "No hyperlink!"
        End If
    Next i

End Sub

运行上面的宏时,引用URLDownloadToFile时出现“编译错误:未定义子函数或函数”。在其他地方,我看到了使用此代码定义的URLDownloadToFile,将其添加到宏后,它就会立即变为红色。

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

将其添加到宏的顶部会使第一行出现语法错误。

我需要下载特殊的补丁程序或库来运行URLDownloadToFile吗?我正在运行Windows 10 64位。还是上述宏有问题?我没有正确定义URLDownloadToFile吗?

1 个答案:

答案 0 :(得分:1)

尝试一下

#If VBA7 And Win64 Then
    Private Declare PtrSafe Function URLDownloadToFile Lib "urlmon" _
      Alias "URLDownloadToFileA" ( _
        ByVal pCaller As LongPtr, _
        ByVal szURL As String, _
        ByVal szFileName As String, _
        ByVal dwReserved As LongPtr, _
        ByVal lpfnCB As LongPtr _
      ) As Long
#Else
    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
#End If

Sub DownloadLinks()
Dim ws As Worksheet
Dim LastRow As Long, i As Long
Dim FolderName as String, strPath As String, strURL As String


    Set ws = Sheets("Sheet1")
    FolderName = "C:\Users\me\Desktop\"
    LastRow = ws.Range("B" & Rows.Count).End(xlUp).Row

    For i = 2 To LastRow

        strURL = ws.Range("C" & i).Value
        If len(strURL) Then
            strPath = FolderName & ws.Range("B" & i).Value & ".jpg"
            Ret = URLDownloadToFile(0, strURL, strPath, 0, 0)

            ws.Range("D" & i).Value = IIf(Ret = 0, _
                                    "File successfully downloaded", _
                                    "Unable to download the file")
        Else
            ws.Range("D" & i).Value = "No URL!"
        End If
    Next i

End Sub