2012-09-04 215 views
2

在VBA中使用URLDownloadToFile,我試圖下載一個文件。問題是一個空白文件正在下載。任何想法爲什麼數據缺失?VBA - URLDownloadToFile - 在下載的文件中丟失數據

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 

Sub Sample() 
    Dim strURL As String 
    Dim strPath As String 

    strURL = "https://abc.abcabc.com/cmif-ku/reports/2012/byOwningEntity/Excel/myfilename.xls" 

    strPath = "C:\Temp\myfilename.xls" 

    Ret = URLDownloadToFile(0, strURL, strPath, 0, 0) 

    If Ret = 0 Then 
     MsgBox "File successfully downloaded" 
    Else 
     MsgBox "Unable to download the file" 
    End If 
End Sub 
+1

兩件事'1)'分享您正在使用的'strURL'。 '2)'你在'strPath'中缺少一個「\」 –

+0

「空白文件」是指一個實際的空的Excel文件或根本沒有文件? –

+0

返回的內容可能不是Excel文件,而是重定向或其他類型的內容? –

回答

1

我有類似的問題。我使用下面的代碼,但得到了一個「溢出」消息:

Sub downloadFile() 
    Dim targetFile As String, targetUrl As String, returnVal As Integer 
    target = "http://www.ishares.com/us/products/239454/ishares-20-year-treasury-bond-etf/1395165510757.ajax?fileType=xls&fileName=iShares-20-Year-Treasury-Bond-ETF" 
    strSavePath = "C:\testdownload.txt" 
    returnVal = URLDownloadToFile(0, target, strSavePath, 0, 0) 
    If returnVal = 0 Then 
     Debug.Print "Download ok!" 
    Else 
     Debug.Print "Error" 
    End If 
End Sub 
1

你得到了溢出,因爲你用一個整數來收集一個長整型值。 urldownloadtofile返回一個長整型值。如果您的下載成功,您將收到「0」。然後你的代碼就可以工作了。