VBA - 迭代列名

时间:2014-09-10 02:37:16

标签: excel vba excel-vba

我在多列中执行相同类型的操作。例如,我的代码目前在我执行此操作时有效:

Cells(lRow, "D") = Cells(lRow, "D") + Cells(lRow + 1, "D")
Cells(lRow, "E") = Cells(lRow, "E") + Cells(lRow + 1, "E")
' .... '
Cells(lRow, "AA") = Cells(lRow, "AA") + Cells(lRow + 1, "AA")
Cells(lRow, "AB") = Cells(lRow, "AB") + Cells(lRow + 1, "AB")

在上面的代码中,我将从D列转到AB列,并在每一列上添加我正在查看的当前行的值以及它下面的行的值。结果代码几乎是30行长,它主要是复制和粘贴,这只是令人讨厌。

我正在尝试重构此代码,以便我可以分解列名称(Cells函数调用中的第二个参数)。我正在考虑使用for循环,从列“D”迭代到列“AB”并执行加法运算。

' iterate from column D to column AB and at each column do the operation below ' 
For c = "D" To "AB"
    Cells(lRow, c) = Cells(lRow, c) + Cells(lRow + 1, c)
Next c

这不起作用,因为看起来VBA不允许对字符进行迭代(for循环)(从“D”变为“AB”)。

我见过其他涉及整数的解决方案,并将它们转换为字符(A = 1,B = 2,C = 3,D = 4等),但无法正常工作。我认为这看起来像这样:

' integer to character mapping: A = 1, B = 2, C = 3, D = 4, ... , AA = 27, AB = 28 '
For i = 4 To 28
    colNameFromInt = Chr(ascii)
    Cells(lRow, colNameFromInt) = Cells(lRow, colNameFromInt) + Cells(lRow + 1, colNameFromInt)
Next i

简而言之,如果我从顶部向您展示了~30行代码,您会如何压缩它?

谢谢!

2 个答案:

答案 0 :(得分:3)

可以使用数字来处理列。由于您已经在使用Cells(),因此只需使用列号而不是字母

Dim c As Integer
For c = 5 To 10
    Cells(1, c) = "this is column " & c
Next c

这会将E列中的单元格更改为I.

或缩短初始示例中的代码

Dim c As Integer
Dim lrow As Long
lrow = 2 ' or however you arrive at a value for this variable

For c = 4 To 28
    Cells(lrow, c) = Cells(lrow, c) + Cells(lrow + 1, c)
Next c

答案 1 :(得分:2)

您可以遍历范围,然后只使用偏移属性 类似的东西:

Dim cel As Range
For Each cel In Range("D1:AB1")
    cel.Offset(lrow - 1, 0) = cel.Offset(lrow - 1, 0) + cel.Offset(lrow, 0)
Next
相关问题