6

我收到以下错误。

Compile error: The code in this project must be updated for use on 64-bit systems.

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\"

它在 Excel 2010 中运行良好。

谢谢。

编辑

我得到的错误是Ret Variable Not defined. 这是其余的代码。

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 & ".mp3"

        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
4

2 回答 2

9

您必须在 64 位版本的 Office 上运行它,而之前您使用的是 32 位版本。

要将 32 位调用转换为 64 位,您通常必须添加PtrSafe到函数并将一些数据类型从转换LongLongPtr(这只是一个更大的数据类型(参见:http: //msdn.microsoft.com/en-us/library/office /gg251378.aspx )

所以转换后的函数将是:

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

编辑:请注意,如果您希望能够在 64 位和 32 位版本的 Office 上使用它,则需要使用预处理器 If 语句,以便 Office 知道要使用哪个函数。IE:

#If Win64 Then
    Private Declare PtrSafe Function URLDownloadToFile Lib "urlmon".......
#Else
    Private Declare Function URLDownloadToFile Lib "urlmon".......
#End If
于 2013-07-02T22:34:14.523 回答
2

MSDN 参考

完整的错误消息:必须更新此项目中的代码才能在 64 位系统上使用。请查看和更新​​ Declare 语句,然后使用 PtrSafe 属性对其进行标记。在 64 位版本的 Microsoft Office 中运行时,所有 Declare 语句现在必须包含 PtrSafe 关键字。PtrSafe 关键字表示 Declare 语句可以安全地在 64 位版本的 Microsoft Office 中运行。将 PtrSafe 关键字添加到 Declare 语句仅表示 Declare 语句明确针对 64 位,语句中需要存储 64 位(包括返回值和参数)的所有数据类型仍必须修改为保存 64 位数量使用用于 64 位积分的 LongLong 或用于指针和句柄的 LongPtr。

添加PtrSafe关键字。

于 2013-07-02T22:32:41.700 回答