Excel VBA:运行时错误:名称为“表0”的查询已存在

时间:2018-10-09 16:27:09

标签: excel vba

此Excel记录的宏有什么问题?当我尝试重新运行它时,它将返回此错误:

Run-time error '-2147024809 (80070057)':
A query with the name 'Table 0' already exists.

当我记录时,它成功地从https://www.timeanddate.com/holidays/us/加载了HTML表。

已由调试VBA编辑器以黄色突出显示的代码

    ActiveWorkbook.Queries.Add Name:="Table 0", Formula:= _
            "let" & Chr(13) & "" & Chr(10) & "    Source = Web.Page(Web.Contents(""https://www.timeanddate.com/holidays/us/""))," & Chr(13) & "" & Chr(10) & "    Data0 = Source{0}[Data]," & Chr(13) & "" & Chr(10) & "    #""Changed Type"" = Table.TransformColumnTypes(Data0,{{""Header"", type text}, {""Date"", type date}, {""Weekday"", type text}, {""Holiday Name"", type text}, {""Holiday Type"", type text}, {""Where It is Observed"", type text}})" & Chr(13) & "" & Chr(10) & "in" & Chr(13) & "" & Chr(10) & "    #""Changed Type"""

完整的VBA脚本

    Sub readTable()
    ' readTable Macro

        ActiveWorkbook.Queries.Add Name:="Table 0", Formula:= _
            "let" & Chr(13) & "" & Chr(10) & "    Source = Web.Page(Web.Contents(""https://www.timeanddate.com/holidays/us/""))," & Chr(13) & "" & Chr(10) & "    Data0 = Source{0}[Data]," & Chr(13) & "" & Chr(10) & "    #""Changed Type"" = Table.TransformColumnTypes(Data0,{{""Header"", type text}, {""Date"", type date}, {""Weekday"", type text}, {""Holiday Name"", type text}, {""Holiday Type"", type text}, {""Where It is Observed"", type text}})" & Chr(13) & "" & Chr(10) & "in" & Chr(13) & "" & Chr(10) & "    #""Changed Type"""
        ActiveWorkbook.Worksheets.Add
        With ActiveSheet.ListObjects.Add(SourceType:=0, Source:= _
            "OLEDB;Provider=Microsoft.Mashup.OleDb.1;Data Source=$Workbook$;Location=""Table 0"";Extended Properties=""""" _
            , Destination:=Range("$A$1")).QueryTable
            .CommandType = xlCmdSql
            .CommandText = Array("SELECT * FROM [Table 0]")
            .RowNumbers = False
            .FillAdjacentFormulas = False
            .PreserveFormatting = True
            .RefreshOnFileOpen = False
            .BackgroundQuery = True
            .RefreshStyle = xlInsertDeleteCells
            .SavePassword = False
            .SaveData = True
            .AdjustColumnWidth = True
            .RefreshPeriod = 0
            .PreserveColumnInfo = True
            .ListObject.DisplayName = "Table_0"
            .Refresh BackgroundQuery:=False
        End With
    End Sub

宏步骤

  1. 选择了数据功能区
  2. 点击获取数据> 从其他来源> 从网络
  3. 基本已选择
  4. URL 字段中,输入https://www.timeanddate.com/holidays/us/
  5. 点击表0 加载
  6. 该表已成功加载到Sheet2中。

0 个答案:

没有答案