尝试从网址

时间:2017-10-21 21:29:36

标签: excel vba excel-vba

我有一个获取URL的vba。 URL(如果插入浏览器)下载.csv文件。 vba应该从URL获取该.csv文件的数据,并将数据添加到新工作表中。

这是必须连接到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

但如果我使用以下URL(也返回.csv文件),我会得到一个例外:

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

两种情况下的CurrentSymbol和dataAddress是相同的。 URL保存网址。

第二个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

我从第二个网址获得的例外情况是:

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

第二个网址有什么问题?

为什么我得到第二个网址的例外?

由于

1 个答案:

答案 0 :(得分:0)

当您的浏览器拥有正确的cookie时,第二个URL仅返回.csv文件。 Excel可能无法提供cookie,因此它会在JSON中收到警告。