URLDownloadToFile 生成编译错误:未定义子或函数
Posted
技术标签:
【中文标题】URLDownloadToFile 生成编译错误:未定义子或函数【英文标题】:URLDownloadToFile generates Compile Error: Sub or Function Not Defined 【发布时间】:2019-06-20 17:17:57 【问题描述】:我正在尝试将图像从 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?我正在运行 64 位的 Windows 10。还是上面的宏有问题?我没有正确定义 URLDownloadToFile 吗?
【问题讨论】:
【参考方案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
【讨论】:
这似乎可行,或者至少没有任何错误。我将在哪里设置图像进入哪个文件夹?看起来图像名称是 B 列和 URL 列 C?感谢您的快速回复! 它是 strPath 的一部分。您的代码正在使用您需要定义的变量 FolderName 我用“C:\Users\Me\TheFolderName”替换了FolderName,宏运行没有错误,但命名文件夹中没有图像。 图片名称是否在 B 列,图片 URL 是否在 C 列? 此代码从 BP 列值中获取图像名称,并从 BP 列超链接地址获取 url。你的名字和网址在哪里?以上是关于URLDownloadToFile 生成编译错误:未定义子或函数的主要内容,如果未能解决你的问题,请参考以下文章
C ++ WinAPI URLDownloadToFile(urlmon)错误[重复]
URLDownloadToFile 失败,代码为 0x800c0008 (INET_E_DOWNLOAD_FAILURE)