Excel 2013 VBA错误

我得到以下错误。

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 

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

要将32位调用转换为64位,通常必须将PtrSafe添加到函数中,并将一些数据types从Long转换为LongPtr (这只是一个更大的数据types)(请参阅http://msdn.microsoft.com/zh-cn/ 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知道使用哪个函数。 即:

 #If Win64 Then Private Declare PtrSafe Function URLDownloadToFile Lib "urlmon"....... #Else Private Declare Function URLDownloadToFile Lib "urlmon"....... #End If 

MSDN参考

完整的错误信息:此项目中的代码必须更新以便在64位系统上使用。 请检查并更新Declare语句,然后用PtrSafe属性标记它们。 在64位版本的Microsoft Office中运行时,所有声明语句现在都必须包含PtrSafe关键字。 PtrSafe关键字指示Declare语句可安全地在64位版本的Microsoft Office中运行。 将PtrSafe关键字添加到Declare语句中仅表示Declare语句显式地以64位为目标,但是需要存储64位(包括返回值和参数)的语句中的所有数据types仍然必须修改以使用64位量用于64位积分的LongLong或用于指针和句柄的LongPtr。

添加PtrSafe关键字。