VBA - URLDownloadToFile - 下载文件中缺少数据

时间:2012-09-04 19:16:59

标签: vba excel-vba excel

在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

2 个答案:

答案 0 :(得分:2)

我有类似的问题。我使用以下代码但得到了#34;溢出"消息:

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 :(得分:1)

你有一个溢出因为你使用了一个整数来收集一个长值。 urldownloadtofile返回一个long值。如果您的下载成功,您将收到“0”。那么你的代码就可以了。