我需要在工作表中使用宏添加一个函数。我需要将一个变量传递给Excel函数,因为它将引用的myWorkbook
和sheetName
是可变的。
MyRange = Workbooks(myWorkbook).Sheets(sheetName).Range("H11:H32")
theFormula = "=SUM(" & MyRange & ")"
Range("B2").Select
ActiveCell.FormulaR1C1 = theFormula
我收到错误13:Type Mismatch
。
我不是一个狂热的VBA程序员,这让我很头疼。我尝试将theFormula
定义为String但没有希望。
答案 0 :(得分:3)
您需要将Range对象转换为范围的字符串表示形式,例如将公式设置为=SUM($H$11:$H$32)
;
Dim MyRange As Range
set MyRange = Workbooks(myWorkbook).Sheets(sheetName).Range("H11:H32")
theFormula = "=SUM(" & MyRange.Address(ReferenceStyle:=xlR1C1) & ")"
Range("B2").Select
ActiveCell.FormulaR1C1 = theFormula
或者如果你不想要R1C1表示法,你可以;
ActiveCell.Formula = "=SUM(H11:H32)"
答案 1 :(得分:2)
Sub MakeSum(sBookName As String, sSheetName As String)
Dim rMyRange As Range
Set rMyRange = Workbooks(sBookName).Sheets(sSheetName).Range("H11:H32")
If rMyRange.Parent.Parent.Name = ActiveWorkbook.Name Then
With ActiveSheet
'same sheet, so just use address
If rMyRange.Parent.Name = .Name Then
.Range("B2").Formula = "=SUM(" & rMyRange.Address & ")"
Else
'same workbook, different sheet, so prepend sheet name
'single quotes prevent error when there's a space in the sheet name
.Range("B2").Formula = "=SUM('" & rMyRange.Parent.Name & "'!" & rMyRange.Address & ")"
End If
End With
Else
'not the same workbook, use external address
ActiveSheet.Range("B2").Formula = "=SUM(" & rMyRange.Address(, , , True) & ")"
End If
End Sub
答案 2 :(得分:-1)
在程序上这不会起作用 - 你说的单元格公式应该等于“= SUM(”& MyRange&“)” - 但是这实际上是什么时候评估的?
是公式= SUM(“& MyRange&”)
工作?