[英]Excel VBA: how to code a Sum formula with variable rows to put in a worksheet
I want to put a Sum formula in a row of a table, in columns C to H, but the code I've come up with somehow doesn't work. 我想将Sum公式放在表格的C到H列中,但是我想出的代码不起作用。 The situation is as follows: 情况如下:
To be more specific and hopefully more clear, let's say that: 为了更具体,希望更清楚,让我们说:
Trying to find out what my code could be, I recorded a macro. 为了找出我的代码是什么,我记录了一个宏。 Based on that I have tested the following code: 基于此,我测试了以下代码:
With Worksheets("A&N")
.Range("C16:H16").Formula = "=SUM(C7:C15)"
End With
This works fine, but as I've described, the numbers 16, 7 and 15 are actually variable. 这很好用,但是正如我所描述的,数字16、7和15实际上是可变的。
I've tried to translate this code to my situation, and made this code: 我尝试将这段代码转换为我的情况,并编写了以下代码:
Set rngOpmaak = Range(rngTabel.Cells(startnum + x, 2), rngTabel.Cells(startnum + x, 7))
rngOpmaak.Formula = "=SUM(“C” & startnum + 3 & “:C” & startnum + x -1)"
When I run the macro I get the message that the second line can't be compiled. 当我运行宏时,我收到一条消息,提示第二行不能编译。 I've seen solutions on this site that to me look exactly like my code, so I don't understand what's wrong with mine. 我在该站点上看到的解决方案对我来说看起来就像我的代码一样,所以我不理解我的问题所在。
I've also tried: 我也尝试过:
rngOpmaak.FormulaR1C1 = "=SUM(R" & startnum + 3 & "C:R" & startnum + x -1 & "C)"
But with startnum=2
(1st row of the table) the formula becomes =SUM(C$3:C$5)
to =SUM(H$3:H$5)
(without the quotations) instead of =SUM(C4:C6)
to =SUM(H4:H6)
. 但是对于startnum=2
(表的第一行),公式将=SUM(C$3:C$5)
变为=SUM(H$3:H$5)
(不带引号),而不是=SUM(C4:C6)
变为=SUM(H4:H6)
。
Can anyone help me with what the line of code should be? 谁能帮助我解决代码行问题? All suggestions are much appreciated. 所有建议,不胜感激。
You'll need to adjust this to your situation, as I didn't use the same variables you did (preferring more expressive ones): 您需要根据自己的情况进行调整,因为我没有使用与您相同的变量(最好使用更具表现力的变量):
Sub test()
Dim output As Range, dataStart As Integer, dataEnd As Integer, rowsOfData As Integer, nCols As Integer
' Row 1: Table headers
' Row 2: 1st row of data
' Row 3: more data
' Row 4: more data
' Row 5: last row of data
' Row 6: Summary row (location of formula)
dataStart = 2
dataEnd = 5
rowsOfData = 1 + dataEnd - dataStart
nCols = 4
Set output = Range(Cells(dataEnd + 1, 1), Cells(dataEnd + 1, nCols))
output.FormulaR1C1 = "=SUM(R[-" & rowsOfData & "]C:R[-1]C)"
End Sub
The generated formula uses relative references, as it was given offsets ( []
) from the current cell, rather than absolute R/C values, eg 所生成的公式使用相对引用,因为它相对于当前单元格有偏移量( []
),而不是绝对R / C值,例如
R2C:R5C -> A$2:A$5
no matter where in column A the formula is entered R2C:R5C -> A$2:A$5
不管在A列中的哪个位置输入公式
R[-4]C:R[-1] -> A2:A5
if the formula is entered in A6 . 如果在A6中输入了公式,则 R[-4]C:R[-1] -> A2:A5
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.