Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Autosum Cells VBA Excel

Tags:

excel

vba

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:

enter image description here

like image 402
Anthony Avatar asked Dec 21 '22 14:12

Anthony


2 Answers

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
like image 108
iDevlop Avatar answered Jan 02 '23 14:01

iDevlop


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
like image 24
Jüri Ruut Avatar answered Jan 02 '23 14:01

Jüri Ruut