vba - Sum of dynamic range
问题描述
To begin with - I can't do that using functions because it is part of a script. Given dummy data of
28
53
32
24
29
25
93
80
20
My formula in Excel is =SUM($A$2:A2)/SUM($A$2:$A$10)
I tried to recreate it in VBA and I am stuck at the part of first parenthesis. Rest I think is fine
Sub testCumulPerc()
Dim ws As Worksheet
Dim wb As Workbook
Dim firstRow As Integer, lastRow As Integer
Dim constSum As Integer
Dim rng As Range
Set wb = Application.ActiveWorkbook
Set ws = wb.Sheets(1)
firstRow = Range("A2").Row
lastRow = Cells(Rows.Count, 1).End(xlUp).Row
constSum = Range("A2").Value
For i = firstRow To lastRow
Set rng = ws.Cells(i, 2)
rng.Value = Application.Sum(constSum, ws.Cells(i, 1)) / Application.Sum(Range(Cells(firstRow, 1), Cells(lastRow, 1)))
Next i
End Sub
It just sums me the 2 given values in first parenthesis, not the range. Also when it comes to the first iteration, it sums A2 with A2 and gives 56 which is not good. The only good calculated percentage is A3 row
Thank you in advance for your help
解决方案
只需根据循环的迭代次数调整开始范围的大小。使用Resize
像这样
sum(range("a2").resize(i-firstrow,1)
推荐阅读
- java - 表单数据未保存在会话中
- powershell - 从另一个 PowerShell 控制台获取数据
- sql - 当星期从星期三开始时,SQLlite 将日期列格式化为星期数
- azure-automation - 没有输出流的 Azure 自动化测试窗格
- python - pytest 的设置时间慢,如何减少?
- javascript - 如何从另一个表制作我的 php 表
- php - PHP MySQL选择最近n分钟内日期时间值的行
- ios - 在 xcode 9 中使用 auk 创建圆形图像
- angular - 下载 PDF 文件、Angular 6 和 Web API
- jquery - 如何在使用 HTML、CSS 和 jQuery 单击简单的 SVG 图标时换掉它?