刷新查询时出错

时间:2018-02-01 03:45:36

标签: excel vba excel-vba

我正在录制一个宏来自动化从网站收集各种股票行情的市盈率信息的过程。该宏涉及两个Web查询。我以完全相同的方式记录它们,并且它们都使用相同的URL。其中一个查询工作正常,另一个提供

  

错误1004“应用程序定义或对象定义的错误”

我已在下面粘贴了该查询的代码。

ActiveWorkbook.Queries.Add Name:="MSFT PE Ratio (TTM) Range, Past 5 Years", _
        Formula:= _
        "let" & Chr(13) & "" & Chr(10) & "    
    Source = Web.Page(Web.Contents(""https://ycharts.com/companies/" & ActiveCell.Value & "/pe_ratio""))," & Chr(13) & "" & Chr(10) & "    Data3 = Source{3}[Data]," & Chr(13) & "" & Chr(10) & "    #""Changed Type"" = Table.TransformColumnTypes(Data3,{{""Column1"", type text}, {""Column2"", type number}, {""Column3"", type date}})" & Chr(13) & "" & Chr(10) & "in" & Chr(13) & "" & Chr(10) & "    #""Changed Type"""

    ActiveWorkbook.Worksheets.Add
    ActiveSheet.Name = "query2"
    With ActiveSheet.ListObjects.Add(SourceType:=0, Source:=Array( _
        "OLEDB;Provider=Microsoft.Mashup.OleDb.1;Data Source=$Workbook$;Location=""" & ActiveCell.Value & "PE Ratio (TTM) Range, Past 5 Years"";Extended Properties=" _
        , """"""), Destination:=Range("$A$1")).QueryTable
        .CommandType = xlCmdSql
        .CommandText = Array( _
        "SELECT * FROM [" & ActiveCell.Value & "PE Ratio (TTM) Range, Past 5 Years]")
        .RowNumbers = False
        .FillAdjacentFormulas = False
        .PreserveFormatting = True
        .RefreshOnFileOpen = False
        .BackgroundQuery = True
        .RefreshStyle = xlInsertDeleteCells
        .SavePassword = False
        .SaveData = True
        .AdjustColumnWidth = True
        .RefreshPeriod = 0
        .PreserveColumnInfo = True
        .ListObject.DisplayName = "_PE_Ratio__TTM__Range__Past_5_Years"
        **.Refresh BackgroundQuery:=False** <-- this is where I get the error
    End With

1 个答案:

答案 0 :(得分:0)

  1. 这是一个Web查询和一个数据库查询的代码。不是两个网页查询。
  2. 两种查询类型都可以使用您可以附加到单元格的参数,并设置为在该单元格更改时自动刷新查询表。
  3. 请参阅:Webquery with parametershttp://dailydoseofexcel.com/archives/2004/12/13/parameters-in-excel-external-data-queries/