简体   繁体   中英

Excel Macro - Error setting cell formula

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.

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)"
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

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?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM