使用 Excel VBA 从不同工作簿引用 Index/Match 公式中的文件路径变量

Referencing File Path variable in Index/Match formula from different workbook with Excel VBA

美好的一天,

我正在尝试使用 Excel VBA 在 Index/Match 公式中引用文件路径变量。 一切都符合 Index/Match 公式,我认为文件路径和工作 sheet 引用是问题所在。 目前,它给出错误 "Run-time Error '1004': Application-defined or object-defined error"

这只是代码的一部分,因为这个宏发生了很多事情,我必须对 8 个不同的文件做同样的事情,这些文件具有不同的名称和不同的 sheet 名称。不同的人会使用宏,主要文件会在不同的文件夹中,因此我必须为文件路径和工作添加变量sheets。

我阅读了很多试图找到解决方案的帖子。很多建议使用 indirectindirect.ext function/formula 但显然 indirect.ext 你必须启用一个附加组件,我不能这样做,因为很多不同的人都会使用这个宏。而 indirect 显然是不稳定的。由于此公式将用于至少 8 个不同的列和超过 50 000 行,因此这似乎不是处理时间的好主意。

在此公式运行之前,将使用代码打开外部工作簿。

这是 Index/Match 公式的代码部分。

Dim path As String
Dim StoreFile As String
Dim StoreFileF As String

path = GetFolder()

StoreFile = Dir(path & "\*Store and Format*.xls*")
StoreFileF = path & "\" & StoreFile

With ws.ListObjects("Table_SDCdata")
    With .ListColumns.Add
        .Name = "Region"
    End With
    .ListColumns("Region").DataBodyRange.Formula = "=INDEX('[" & StoreFileF & "]Worksheet[1]'!F:F,MATCH([@Site],'[" & StoreFileF & "]Worksheet[1]'!A:A)0,1)"
End With

任何建议或帮助将不胜感激。

方括号仅文件名

    path = "c:\path\to\file"
    file = "My Workbook.xlsx"
    sheetname = "Sheet Name"

    ref = path & "\[" & file & "]" & sheetname
    sFormula = "=INDEX('" & ref & "'!$F:$F,MATCH([@Site],'" & ref & "'!$A:$A,0),1)"
    Debug.Print sFormula

    With ws.ListObjects("Table_SDCdata")
    With .ListColumns.Add
        .Name = "Region"
    End With
        .ListColumns("Region").DataBodyRange.Formula = sFormula
    End With