2017-10-21 346 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

相关问题