Im trying to autosum the values within a block of cells in Excel using VBA. I kept getting a type mismatch error while debugging the following code. Where did I go wrong?
Sub autosumtest()
    Dim total As Integer
    Worksheets("Sheet1Test").Select
    Range("F16:G20").Select
    total = CInt("=SUM(Selection.Values)")
    MsgBox (total)
End Sub
EDIT 1: Here is the simple sample of my test data called Autosum Range:

You can use the [] to evaluate any spreadsheet expression.
Sub autosumtest()
   Dim total As Integer
   total = CInt([=sum(sheet1Test!F16:G20)])
   MsgBox (total)
End Sub
                        Yes, there's a type mismatch, as "=SUM(F16:G20)" is a string.
Worksheetfunction should be used for summing a desired range. Unless there's a wish to something further with selection, .Select is not needed.
Option Explicit
Sub autosumtest()
    Dim total As Integer
    Dim rng As Range
    Set rng = Worksheets("Sheet1Test").Range("F16:G20")
       total = CInt(WorksheetFunction.Sum(rng))
    MsgBox (total)
End Sub
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With