2013-10-08 65 views
0

我正試圖用2個變量寫單元格的公式。 式細胞應該是:VBA FormulaR1C1語法與變量

=(SUM('C:\Users\[Excel.xlsm]Sheet1'!H:H)-SUM('C:\Users\[Sheet1.xlsm]Sheet1'!I:I)) 

我想使用文件路徑作爲變量,以及表名稱。

path = C:\Users\Excel.xlsm 'from msofiledialog 
sheetname = Sheet1 

我在想什麼?

Cells(1, 1).FormulaR1C1 = "=(SUM('[" & Path & "] " & sheetname & " '!C8) _ 
         -SUM('[" & Path & "] " & sheetname & " '!C9)) 

回答

0

感謝,這爲我工作:

Sub main 
Dim LastRow as String 
LastRow = Cells(Rows.Count, 1).End(xlUp).Row 
Dim path as String 
Path = "C:\users\username\Desktop\" 
Dim filename as String 
Filename = "Excel.xlsm" 
Dim sheetname as String 
sheetnameCR = "CR_" & supname 
Dim myrangeH as String 
Dim myrangeI as String 
myrangeH = ("H5:H" & LastRow) 
myrangeI = ("I5:I" & LastRow) 

Cells(1, 1).Formula = "=SUM('" & Path & "[" & Filename & "]" & sheetnameCR & "'!" & myrangeH & ")" & "-SUM('" & Path & "[" & Filename & "]" & sheetnameCR & "'!" & myrangeI & ")" 
End Sub 

我不得不添加 「RangeH」 變量,否則Excel中拿了細胞C8,而不是H列,這是我想要的。 這很好,但即使我給他完整的路徑到所需的單元格,Excel仍然要求我的路徑與FileDialogOpen出色。任何想法爲什麼?

+0

當我鍵入它是這樣的: Cells(1,1).FormulaR1C1 =「=(SUM('C:/ Users /」&Environ $(「Username」)&「/Desktop/[Excel].xlsm ]「&sheetnameCR&」'!C8)-SUM('C:/ Users /「&Environ $(」Username「)&」/Desktop/[Excel].xlsm]「&sheetnameCR&」'!C9))「 它不是問我路徑或任何東西,我只是希望它稍微短一些。 –