2017-10-21 348 views
0

我有一個vba,它獲取一個URL。 URL(如果插入到瀏覽器中)下載.csv文件。 vba應該從URL獲取該.csv文件的數據,並將數據添加到新工作表。嘗試從URL獲取數據時出現異常

這是必須連接到URL和獲取數據的代碼:

  With Sheets(currentSymbol).QueryTables.Add(Connection:= _ 
       "TEXT;" & URL _ 
       , Destination:=Sheets(currentSymbol).Range(dataAddress)) 
       .Name = "" 
       .FieldNames = True 
       .RowNumbers = False 
       .FillAdjacentFormulas = False 
       .PreserveFormatting = True 
       .RefreshOnFileOpen = False 
       .RefreshStyle = xlOverwriteCells 
       .SavePassword = False 
       .SaveData = True 
       .AdjustColumnWidth = True 
       .RefreshPeriod = 0 
       .TextFilePromptOnRefresh = False 
       .TextFilePlatform = 850 
       .TextFileStartRow = 2 
       .TextFileParseType = xlDelimited 
       .TextFileTextQualifier = xlTextQualifierDoubleQuote 
       .TextFileConsecutiveDelimiter = False 
       .TextFileTabDelimiter = False 
       .TextFileSemicolonDelimiter = False 
       .TextFileCommaDelimiter = True 
       .TextFileSpaceDelimiter = False 
       .TextFileColumnDataTypes = Array(2, 2, 2, 2, 2, 2, 9) 
       .TextFileTrailingMinusNumbers = True 
       .Refresh BackgroundQuery:=False 
      End With 

如果我用下面的URL(即返回.csv文件),它工作得很好:

http://www.google.com/finance/historical?q=SPY&startdate=Jan+1%2C+2000&enddate=Dec+31%2C+2017&num=30&ei=WLQtWaAfiMOxAbeYutgE&output=csv

但是,如果使用下面的網址(也返回.csv文件),我得到一個異常:

https://query1.finance.yahoo.com/v7/finance/download/SPY?period1=1476219600&period2=1508533200&interval=1d&events=history&crumb=uqY5qLCvV0S

CurrentSymbol和dataAddress在兩種情況下都是相同的。 網址包含網址。

第二個URL確實存在,並且返回一個.csv文件。

我有一個前檢查爲完成罰款(兩個網址)的網址:

Function HttpExists(sURL As String) As Boolean 
    Dim oXHTTP As Object 
    Set oXHTTP = CreateObject("MSXML2.ServerXMLHTTP") 

On Error GoTo haveError 
oXHTTP.Open "HEAD", sURL, False 
oXHTTP.send 
HttpExists = IIf(oXHTTP.status = 200, True, False) 
Exit Function 

,我從第二URL得到異常說:

Error 1004: Microsoft excel cannot access the file "https://.........." 
There are several posible reasons: 
* The file name of path does not exist 
* The file is being used by another program 
* The workbook you are trying to save the same name as a currently open workbook 

能有什麼成爲第二個網址的問題?

爲什麼我會得到第二個URL的例外情況?

感謝

+0

HTTPS已加密。您可能必須下載CSV文件,然後打開並閱讀它。 – MatthewD

+0

有沒有辦法自動做到這一點?這是一個腳本,通過超過1000個這樣的網址.. – alon

回答

0

第二URL只返回一個.csv文件時,您的瀏覽器有正確的cookie。 Excel可能無法提供cookie,因此它在JSON中收到警告。

+0

謝謝..有沒有辦法自動做到這一點?它是一個腳本,通過超過1000個這樣的URL – alon

+0

您可以跳過它使用舊的'On Error Resume Next' – itsLex

+0

但我不想跳過它..我需要.csv中的數據..有沒有辦法使用它? – alon

相關問題