2013-07-02 133 views
6

我收到以下錯誤。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 

回答

9

您必須在Office的64位版本上運行此功能,而以前您使用的是32位版本。

要轉換32位調用64位您通常需要添加PtrSafe的功能和一些從Long中的數據類型轉換爲LongPtr(這僅僅是一個更大的數據類型(參見: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位版本,則需要如果語句,這樣辦公室知道要使用哪個函數使用預處理即:

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

非常感謝,但我也應該添加其他代碼。我之前得到的錯誤是修復感謝,但我得到錯誤,'Ret'變量未定義。 – Mowgli

+1

沒有probs。您還需要將'Ret'變量從'Long'轉換爲'LongPtr',因爲這是該函數的新返回類型。 (如果它是一個全局變量,那麼使用'Public'(或'Private'作爲該模塊)而不是'Dim') – CuberChase

+0

嗨,對不起,我剛剛有時間。但我嘗試添加LongPtr,並嘗試公開但它沒有工作。我該怎麼辦?謝謝 – Mowgli

2

MSDN reference

完整的錯誤消息: 此項目中的代碼必須在64位系統 使用進行更新。請檢查並更新Declare語句和 ,然後用PtrSafe屬性標記它們。所有聲明聲明必須 現在在Microsoft Office的64位版本 中運行時包含PtrSafe關鍵字。 PtrSafe關鍵字表示聲明語句是 可安全地在64位版本的Microsoft Office中運行。在Declare語句中添加PtrSafe 關鍵字僅表示Declare語句 顯式指向64位, 需要存儲64位(包括返回值和參數)必須 的語句內的所有數據類型仍必須修改爲保存64位使用LongLong爲 64位積分或LongPtr指針和句柄。

添加PtrSafe關鍵字。