格式接入小區中的片材在外部工作簿是
'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