2017-09-13 107 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個多小時試圖弄清楚這一點,我很高興我尋求幫助。 :) 再次感謝你的幫助。 –