VBA公式:变量文件名和变量表名称

时间:2017-09-13 00:36:40

标签: excel vba excel-vba excel-formula

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

  • SourceFileNamePath =我链接到的工作簿的路径和名称
  • SourceTab =我要链接到的工作簿中的标签

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

代码如下:

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

1 个答案:

答案 0 :(得分:3)

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

'path\[filename]sheetname'!cell_reference

因此,如果您有一个名为SourceFileNamePath的变量,其中包含路径文件名(例如"C:\Temp\Data\Book1.xlsx"),那么您需要将文件名与路径分开。

您可以使用以下内容:

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

注意:如果路径或文件名包含任何单引号(例如,如果文件名为Sukhbir's test file.xlsx),则需要对其进行转义(即每个单引号需要由两个单引号替换)单引号)。这可以通过使用Replace函数来实现,例如:

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