【问题标题】:How do you get the file name of the data source of an Excel table into a cell?如何将Excel表格的数据源的文件名放入单元格中?
【发布时间】:2021-06-23 20:09:47
【问题描述】:

我在工作表“材料数据”上有一个名为“材料”的表,该表从另一个工作簿获取数据。我希望能够检索外部工作簿文件(“data.xlsm”)的名称并将其显示在单元格中。我无法找到它在 Excel VBA 对象模型中的存储位置。

Sub GetConnection()
   Dim ConSource As String
   Dim ws As Worksheet

   Set ws = Sheets("Material Data")

   ConSource = ws.ListObjects("Materials").QueryTable.Connection
   'ConSource = ws.ListObjects("Materials").QueryTable.SourceDataFile

   Worksheets("Quote").Range("A15").Value = ConSource

   ConSource = ""

End Sub

QueryTable.Connection 和 QueryTable.SourceDataFile 属性都没有存储外部数据源的文件路径。我应该在哪里寻找?谢谢!

编辑:我也试过.QueryTable.SourceConnectionFile;它也没有任何东西。

【问题讨论】:

  • .QueryTable.SourceConnectionFile 是什么?
  • @CDP1802,对不起,我应该说,我也试过那个,但它也没有任何东西。
  • ws.ListObjects("Materials").SourceType = 3 ?.
  • @CDP1802,是的。

标签: excel vba datasource


【解决方案1】:

嗯,它不是孤立在它自己的对象属性中的,但我确实通过解析“Power Query M”公式字符串找到了源文件路径。以下代码有效:

Sub GetConnection()
    Dim conSource, powerQueryMFormula As String
    Dim formulaChunks() As String
   
    powerQueryMFormula = ThisWorkbook.Queries("Materials").Formula

    'Split the formula string at every double quotation mark.
    formulaChunks = Split(powerQueryMFormula, Chr(34), 3) 'Chr(34) = double quotation mark.
    conSource = formulaChunks(1)

    Worksheets("Quote").Range("A15").Value = conSource

    conSource = ""
    powerQueryMFormula = ""
    
End Sub

【讨论】:

    猜你喜欢
    • 2020-08-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多