2017-09-13 106 views
2

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

  • SourceFileNamePath =前进,我链接到
  • SourceTab =选项卡中我要链接到

虽然代码运行正常工作簿簿的名称,所产生的公式是行不通的。有没有人有任何想法,我是否正确引用SourceFileNamePathSourceTab

代码如下:

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

只有文件名** **应该用括号括起来实现 - 例如'= 'C:\温度\数据\ [Book1.xlsx] SHEET2' R5C10'!。 (请参阅[此问题](https://stackoverflow.com/q/46162966/6535336)以了解可能的设置方式。) – YowE3K

回答

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 
+0

非常感谢,这个工作非常完美!我昨天花了3个多小时试图弄清楚这一点,我很高兴我寻求帮助。 :) 再次感谢你的帮助。 –