我是VBA的新手。我试图使用循环来执行sumif函数。我希望函数在经过时更改其sum_range标准。
我首先尝试使用以下代码:
While cls <= num_cols
While rws <= num_rows
Cells(rws, cls).Value = "=SUMIF('BW YTD - Act&Plan'!$C:$C,A" & rws & ",'BW YTD - Act&Plan'!D:D)"
rws = rws + 1
Wend
rws = 7
cls = cls + 1
Wend
正如您在代码中注意到的那样,sum_range是D:D。我希望能够循环并在下一次将其更改为E:E并继续前进,直到我到达最后一列。
我将其硬编码如下:
While rws <= num_rows
Cells(rws, 2).Value = "=SUMIF('BW YTD - Act&Plan'!$C:$C,A" & rws & ",'BW YTD - Act&Plan'!D:D)"
rws = rws + 1
Wend
rws = 7
While rws <= num_rows
Cells(rws, 3).Value = "=SUMIF('BW YTD - Act&Plan'!$C:$C,A" & rws & ",'BW YTD - Act&Plan'!E:E)"
rws = rws + 1
Wend
rws = 7
While rws <= num_rows
Cells(rws, 4).Value = "=SUMIF('BW YTD - Act&Plan'!$C:$C,A" & rws & ",'BW YTD - Act&Plan'!F:F)"
rws = rws + 1
Wend
rws = 7
While rws <= num_rows
Cells(rws, 5).Value = "=SUMIF('BW YTD - Act&Plan'!$C:$C,A" & rws & ",'BW YTD - Act&Plan'!G:G)"
rws = rws + 1
Wend
rws = 7
任何建议都将不胜感激。
答案 0 :(得分:1)
您可以使用for循环,chr()
函数将整数转换为字母。 (cls + 64 + 2)
允许您为“B”说cls = 2
,然后添加64得到66,这是“B”的ASCII字符。要抵消,如果cls = 2
会给你“D”,只需添加额外的2.(你当然可以把它合并为chr(cls + 66)
,但我想证明为什么它会是66。)< / p>
While cls <= num_cols
While rws <= num_rows
Cells(rws, cls).value = "=SUMIF('BW YTD - Act&Plan'!$C:$C,A" & rws & _
",'BW YTD - Act&Plan'!" & Chr(cls + 64 + 2) & ":" & Chr(cls + 64 + 2) & ")"
rws = rws + 1
Wend
rws = 7
Wend