带变量的VBA FormulaR1C1语法

时间:2013-10-08 21:11:19

标签: vba variables syntax

我正在尝试将2个变量的公式写入单元格。 细胞中的公式应该是:

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

我希望使用path作为变量以及工作表名称。

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

我错过了什么?

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

1 个答案:

答案 0 :(得分: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获得优秀的路径。知道为什么吗?