Reputation: 21
I need to add a function in my worksheet using macros. I need to pass a variable to the Excel function since myWorkbook
and sheetName
, to which it will reference, are variable.
MyRange = Workbooks(myWorkbook).Sheets(sheetName).Range("H11:H32")
theFormula = "=SUM(" & MyRange & ")"
Range("B2").Select
ActiveCell.FormulaR1C1 = theFormula
I get error 13: Type Mismatch
.
I am not an avid VBA programmer, and this is giving me a big headache. I tried defining theFormula
as String but no hope.
Upvotes: 2
Views: 2654
Reputation: 33145
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
Upvotes: 2
Reputation: 175816
You need to convert the Range object to a string representation of the range, for example to set the formula to =SUM($H$11:$H$32)
you would;
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
Or if you dont want R1C1 notation you can;
ActiveCell.Formula = "=SUM(H11:H32)"
Upvotes: 3
Reputation: 1255
Progragmatically this wont work - you are saying the cell formula should equal "=SUM(" & MyRange & ")" - however when is this actually evaluated ?
does theFormula =SUM(" & MyRange & ")
work?
Upvotes: -1