0

我正在尝试将具有 2 个变量的公式写入单元格。单元格中的公式应为:

=(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))
4

1 回答 1

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 进行 excel 的路径。知道为什么吗?

于 2013-10-09T08:53:29.833 回答