格式接入小区中的片材在外部工作簿是
'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
只有文件名** **应该用括号括起来实现 - 例如'= 'C:\温度\数据\ [Book1.xlsx] SHEET2' R5C10'!。 (请参阅[此问题](https://stackoverflow.com/q/46162966/6535336)以了解可能的设置方式。) – YowE3K