Excel 2013 VBA错误

Mow*_*gli 6 excel 64-bit vba excel-2013

我收到了以下错误.

Compile error: The code in this project must be updated for use on 64-bit systems.
Run Code Online (Sandbox Code Playgroud)

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\"
Run Code Online (Sandbox Code Playgroud)

它在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
Run Code Online (Sandbox Code Playgroud)

Cub*_*ase 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
Run Code Online (Sandbox Code Playgroud)

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

#If Win64 Then
    Private Declare PtrSafe Function URLDownloadToFile Lib "urlmon".......
#Else
    Private Declare Function URLDownloadToFile Lib "urlmon".......
#End If
Run Code Online (Sandbox Code Playgroud)