简体   繁体   中英

sum of decimals in excel vba

I want to sum the cells of one column using excel vba. The values in the cells are deimals, however, the sum given by excel vba is always an integer. For example: 2.5 +2.1 = 4.6 excel will display 5. How can I show the 4.6 value?

Thank you for your help.

Use the Double data type:

Sub SumTheValues()
    Dim zum As Double
    zum = Application.WorksheetFunction.Sum(Range("A:A"))
    MsgBox zum
End Sub

For your data:

在此处输入图片说明

I found from another post. Option 4 to be the best - https://www.exceltrick.com/how_to/sum-cells-based-on-background-color

I then took what was above and replace one word - "as long" to "as double" and now the function works perfectly with colors.

Function SumByColor(CellColor As Range, rRange As Range)
Dim cSum As Double
Dim ColIndex As Integer
ColIndex = CellColor.Interior.ColorIndex
For Each cl In rRange
  If cl.Interior.ColorIndex = ColIndex Then
    cSum = WorksheetFunction.sum(cl, cSum)
  End If
Next cl
SumByColor = cSum
End Function

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