excel - 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
”?最后一个问题可能是第一个问题的“修复”,如果它是分隔符“,”,那可能会造成麻烦?
谢谢
姜小子
解决方案
测试和工作正常
- 声明你的变量
- 您需要使用工作表来限定您的对象
- 无需在
Screen Updating
此处关闭。您只是在修改一个单元格
此代码将放置Value
inA1
和Formula
inB1
免责声明:
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
推荐阅读
- c++ - c++ 致命错误:glad/gl.h: No such file or directory
- java - Mockito for Spring JPA Specification API 不完全执行动态查询
- r - 从 gfortran 调用 Lapack DLL
- maven - 在 Anypoint 平台 (CloudHub) 中使用 Jenkins 部署时出现错误 409 冲突
- sql-server - 如何通过 SQL Server 插入的索引有效地替换长字符串?
- javascript - 如何使用 javascript 或 jquery post 方法从循环中发送变量并使用 php 接收
- r - 如何在 gitbook 风格的 bookdown 中使用 gitbook 插件
- macos - macOS Catalina 内核调试
- matlab - 行向量的连续数字之和并将它们存储在该位置
- python - 为什么当我设置 while var != 0 时循环不会在 0 计数处中断