首页 > 解决方案 > Excel VBA 将值加起来/加起来,即使是逗号/小数点

问题描述

我有一个问题,我不能添加带小数的数字。只有没有小数的数字。

我编写了一个代码来总结来自不同单元格的值。只要数字没有小数,这项工作就很好。

这是我的代码:

Sub SumValues()

'This makro is made to add values together depending on 
'x amount of Sheets in the workbook:
Application.ScreenUpdating = False

'A will sum up the values from each cell, 
'depending on the amount of Sheets  in the this Workbook:
A = 0

For I = 1 To ThisWorkbook.Sheets.Count
    'Adding the values from cell E5 to Cells(5, 5 + (I - 1) * 3), 
    'with the distance 3 between each cell:
    A = A + Cells(5, 5 + (I - 1) * 3)
Next I

'The values A that is added togheter from the cells, is now put in a cell:
Worksheets("Sheet1").Cells(1, 1).Formula = "=" & A & ""
Application.ScreenUpdating = True

End Sub

因此,对于 3 张纸,“I”从 1 变为 3。因此,如果我的单元格包含这些数字:

Cell(5,5) = 2

Cell(5,8) = 3

Cell(5,11) = 8

我得到总和Cell(1,1) = 13

但如果我有这些价值观:

Cell(5,5) = 2,2

Cell(5,8) = 3

Cell(5,11) = 8

运行脚本时收到“运行时错误'9':下标超出范围”错误消​​息。有什么建议么?

另一个问题是是否可以将公式放入我正在添加值的单元格中?例如,如果我的工作簿中有 3 张工作表,它将汇总来自Cell(5,5)Cell(5,8)的值Cell(5,11)。总和显示在 中Cell(1,1)。但我得到的只是数字,而不是公式。是否可以让单元格显示公式“ =E5+H5+K5”?最后一个问题可能是第一个问题的“修复”,如果它是分隔符“,”,那可能会造成麻烦?

谢谢

姜小子

标签: excelvbasumdecimalcell

解决方案


测试和工作正常

  1. 声明你的变量
  2. 您需要使用工作表来限定您的对象
  3. 无需在Screen Updating此处关闭。您只是在修改一个单元格

此代码将放置ValueinA1FormulainB1


免责声明:

Type Mismatch Error如果您将任何具有非数值值的单元格输入到循环中,您的代码和下面的代码可能会受到影响。如果任何非数字单元格有可能在总和范围内,则可以通过在循环中嵌套类似以下内容来避免错误:If ISNUMERIC(Range) Then.


Sub SumValues()

Dim ws As Worksheet: Set ws = ThisWorkbook.Sheets("Sheet1")
Dim A As Double, i As Long, Loc As String

For i = 1 To ThisWorkbook.Sheets.Count
    A = A + ws.Cells(5, (5 + (i - 1) * 3))
    Loc = ws.Cells(5, (5 + (i - 1) * 3)).Address(False, False) & "+" & Loc
Next i

ws.Range("A1") = A
ws.Range("B1").Formula = "=" & Mid(Loc, 1, Len(Loc) - 1)

End Sub

推荐阅读