【问题标题】:VBA Formula: Variable File Name and Variable Sheet NameVBA 公式:变量文件名和变量表名
【发布时间】:2017-09-13 00:36:39
【问题描述】:

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

  • SourceFileNamePath = 我要链接的工作簿的路径和名称
  • SourceTab = 我要链接到的工作簿中的选项卡

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

代码如下:

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

【问题讨论】:

  • 只有文件 name 应该用括号括起来 - 例如='C:\Temp\Data\[Book1.xlsx]Sheet2'!R5C10。 (有关可能的设置方式,请参阅this question。)

标签: vba excel excel-formula


【解决方案1】:

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

'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

【讨论】:

  • 非常感谢,这非常有效!我昨天花了 3 个多小时试图解决这个问题,我很高兴我寻求帮助。 :) 再次感谢您的帮助。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-12-14
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多