如何在特定范围的每一行右侧的单元格中执行函数?

时间:2015-01-28 13:47:14

标签: excel vba loops excel-vba split

早些时候我试图在下面的单元格中对每个范围的每一列求和并得到成功帮助。我只是想修改我收到的代码,为每一行做同样的事情,并在右边的列中得到结果

Sub miine()

Dim a, i As Integer, Data, sums As Range
a = InputBox("How many cells for the square?")
Set Data = Range(ActiveCell.Offset(0, 0), ActiveCell.Offset(a - 1, a - 1))

Set sums = Range(ActiveCell.Offset(a, 0), ActiveCell.Offset(a, a - 1))
For Each cell In sums
cell.Value = "=SUM(" & Split(cell.Address, "$")(1) & cell.Row - a & ":" & Split(cell.Address, "$")(1) & cell.Row - 1 & ")"
Next

Set sum = Range(ActiveCell.Offset(0, a), ActiveCell.Offset(a - 1, a))
For each cell in sum
cell.Value = "=SUM(" & cell.Column - a & Split(cell.Address, "$")(2) & ":" & cell.Column - 1 & Split(cell.Address, "$")(2) & ")"

End Sub

第二部分不起作用,我在右边得到了总和,但为总和选择的范围看起来像Range(11:41)而不是Range(“A1:D1”)。提前致谢

1 个答案:

答案 0 :(得分:0)

Cell.Address是这样的:“$A$1”;函数Split按符号$拆分,因此字母A将包含在数组的(1)位置,而行号1位于该位置(2)。这就是你的原因:

Split(cell.Address, "$")(2)  

返回一个数字而不是一个字母。你想做的可能是:

Set sum = Range(ActiveCell.Offset(0, a), ActiveCell.Offset(a - 1, a))
For each cell in sum
    cell.Value = "=SUM(" & Split(cell.Offset(0,-a).Address,"$")(1) & cell.Row & ":" & Split(cell.Offset(0,-1).Address,"$")(1) & cell.Row & ")"  
Next cell