Discussion Locked

Excel VBA

0 helpful
6 replies
Closed to new repliesThis discussion is closed. It stays readable, but it takes no new replies.
I need to perform calculations under a button is there any place where I can select a range then total it using vba

6 replies

by bill_h

The following code, executed in response to a click on a button named "cmdSumNumbers", will create a Range object for cells A1 through C5, and then display a message box with the sum of that range:

Private Sub cmdSumNumbers_Click()
Dim xlAppAs Excel.Application
Dim xlWSheet As Excel.Worksheet
Dim xlRange As Excel.Range

Set xlApp = New Excel.Application
xlApp.Workbooks.Open "Book1.xls"
Set xlWSheet = xlApp.Worksheets("Sheet1")
Set xlRange = xlWSheet.Range("A1:C5")
'Set xlRange = xlWSheet.Range(xlWSheet.Cells(1, 1), xlWSheet.Cells(5, 3))

'Display result of Sum function
MsgBox "Answer is " & xlApp.WorksheetFunction.Sum(xlRange)

Set xlRange = Nothing
Set xlWSheet = Nothing Set xlApp = Nothing
End Sub

The second "Set xlRange" statement that is commented out shows how the "Cells(x,y)" notation can be used to specify a range. The advantage to using the "Cells(x,y)" notation is that variables can be used to selectthe beginning and ending cells for the range, rather than hard-coding a cell reference like "A1".

The "WorksheetFunction" object serves as a container for the function.

Hope this helps...

by bill_h

Pursuant to your e-mail response --

The MsgBox statement is just an example. The key is the code fragment "WorksheetFunction.Sum(xlRange)", which returns the sum of the cells in the specified range. I've modified the routine to set the value ofcell "A6" to the sum of the specified range:

Private Sub cmdSumNumbers_Click()
Dim xlRange As Range

Set xlRange = Sheet1.Range("A1:C5")
'Set xlRange = xlWSheet.Range(xlWSheet.Cells(1, 1), xlWSheet.Cells(5, 3))

'Display result of Sum function
Sheet1.Range("A6").Value = Application.WorksheetFunction.Sum(xlRange)

Set xlRange = Nothing
End Sub

by steve barrow

Add this to your click event and modify the output cell as required.
eg if at the end of the selected sequece the use a function to return the last item selected and add one to the resultant cell - can write for you if you are not sure how to do this.

Sub sumit()
'get the currently selected cells
'note if selected cell = a1 then a circular ref error will occur
'create a function in cell a1 - or any cell you choose
Range("a1").Formula = "=sum(" & ActiveWindow.RangeSelection.Address & ")"
End Sub

Hope this helps.

Steve.

This discussion is closed to new replies.