VBA公式:variables文件名和variables表名称

我正在尝试在另一个工作簿中创build单元格引用。 在我的代码下面,我正在使用工作簿名称和工作表名称的variables。

  • SourceFileNamePath =我链接到的工作簿的path和名称
  • SourceTab =我要链接到的工作簿中的Tab

虽然代码运行正常,但生成的公式不起作用。 有没有人有任何想法,我是否正确引用SourceFileNamePathSourceTab

代码如下:

 Cells(destStartRow, destStartCol).FormulaR1C1 = "='[" & SourceFileNamePath & "]" & SourceTab & "'!R" & sourceStartRow & "C" & sourceStartCol 

访问外部工作簿中工作表中单元格的格式为

'path\[filename]sheetname'!cell_reference

所以如果你有一个名为SourceFileNamePath的variables,包含path文件名(例如"C:\Temp\Data\Book1.xlsx" ),那么你需要将文件名与path分开。

你可以使用像这样的东西:

 SourceFileNamePath = "C:\Temp\Data\Book1.xlsx" ' or however you set that variable SourceTab = "Sheet1" ' or however you set that variable Dim SourceFilePath As String Dim SourceFileName As String SourceFilePath = Left(SourceFileNamePath, InStrRev(SourceFileNamePath, Application.PathSeparator)) SourceFileName = Mid(SourceFileNamePath, InStrRev(SourceFileNamePath, Application.PathSeparator) + 1) Cells(destStartRow, destStartCol).FormulaR1C1 = "='" & SourceFilePath & "[" & SourceFileName & "]" & SourceTab & "'!R" & sourceStartRow & "C" & sourceStartCol 

注意:如果path或文件名包含任何单引号(例如,如果文件名是Sukhbir's test file.xlsx文件Sukhbir's test file.xlsx ),那么它将需要被转义(即每个单引号需要被两个单引号分数)。 这可以通过使用Replacefunction来实现,例如:

 Cells(destStartRow, destStartCol).FormulaR1C1 = _ "='" & Replace(SourceFilePath, "'", "''") & _ "[" & Replace(SourceFileName, "'", "''") & "]" & _ SourceTab & "'!R" & sourceStartRow & "C" & sourceStartCol