如何在 Excel 2013 VBA 中使用 .odc 文件导入数据

how to import data using .odc file in Excel 2013 VBA

我正在尝试编写一些 VBA,使用存储在 SharePoint 数据连接库中的 .odc 文件将一些数据导入查询 table。我使用宏记录器记录了我添加连接的过程,然后转到现有连接并将数据导入当前工作表中的 table (当我手动完成时有效)。

记录器吐出以下代码(我删除了命令文本,因为它包含一些敏感信息,但它是一大串与 SharePoint 相关的内容,例如列表和视图 GUID):

Sub RecordedImportMacro()

    Workbooks("MyWorkbook.xlsm").Connections.AddFromFile _
        "http://path/to/my/odcfile/on/sharepoint.odc"
    With ActiveSheet.ListObjects.Add(SourceType:=0, Source:= _
        "OLEDB;Provider=Microsoft.Office.List.OLEDB.2.0;Data Source="""";ApplicationName=Excel;Version=12.0.0.0" _
        , Destination:=Range("$A")).QueryTable
        .CommandType = 5
        .CommandText = "some command text here"
        .RowNumbers = False
        .FillAdjacentFormulas = False
        .PreserveFormatting = True
        .RefreshOnFileOpen = False
        .BackgroundQuery = False
        .RefreshStyle = xlInsertDeleteCells
        .SavePassword = False
        .SaveData = True
        .AdjustColumnWidth = True
        .RefreshPeriod = 0
        .PreserveColumnInfo = True
        .SourceConnectionFile = "http://path/to/my/odcfile/on/sharepoint.odc"
        .ListObject.DisplayName = "My_Table"
    End With
End Sub

然而,当我 运行 宏似乎执行与之前工作完全相同的任务时,我收到以下错误:运行 时间错误 1004。我用谷歌搜索并没有真正找到任何与我的用例有关的东西

当我调试时,以下行被突出显示:.CommandType = 5

关于如何让它工作有什么想法吗?

我能够使用找到的代码使其工作 here

代码如下:

Sub ThisWorks()

    With ActiveSheet.QueryTables.Add(Connection:= _
        "FINDER;http://path/to/my/odcfile/on/sharepoint.odc" _
        , Destination:=Range("$A"))
        .RefreshStyle = xlInsertDeleteCells
        .RowNumbers = False
        .FillAdjacentFormulas = False
        .RefreshOnFileOpen = True
        .HasAutoFormat = True
        .BackgroundQuery = True
        .TablesOnlyFromHTML = True
        .Refresh BackgroundQuery:=False
        .SavePassword = False
        .SaveData = True
    End With

End Sub