简体   繁体   English

如何在Excel VBA中的范围内循环列

[英]How do you loop columns within a range in Excel VBA

The title may be similar to other questions but as far as I can tell no one has asked this one. 标题可能与其他问题类似,但据我所知,没有人问过这个问题。 I am trying to loop through all columns and add the sum of them at the bottom after the last row and make the values before the sum grey. 我试图遍历所有列,并将它们的总和添加到最后一行之后的底部,并在总和之前添加值。 Up until this point I have been writing out each column name but the sheets keep getting larger and this is becoming a waste of time because I know there must be a better way. 到现在为止,我一直在写出每个列的名称,但是工作表越来越大,这正浪费时间,因为我知道必须有更好的方法。 Please keep in mind I am new to VBAs. 请记住,我是VBA的新手。 The section of the code is: 代码部分是:

LR = Range("I" & Rows.Count).End(xlUp).Row
Range("I1:I" & LR & "").Interior.Color = RGB(217, 217, 217)
Range("I" & LR + 2).Formula = "=SUM(I2:I" & LR & ")"
LR = Range("J" & Rows.Count).End(xlUp).Row
Range("J1:J" & LR & "").Interior.Color = RGB(217, 217, 217)
Range("J" & LR + 2).Formula = "=SUM(J2:J" & LR & ")"
LR = Range("K" & Rows.Count).End(xlUp).Row
Range("K1:K" & LR & "").Interior.Color = RGB(217, 217, 217)
Range("K" & LR + 2).Formula = "=SUM(K2:K" & LR & ")"
LR = Range("L" & Rows.Count).End(xlUp).Row
Range("L1:L" & LR & "").Interior.Color = RGB(217, 217, 217)
Range("L" & LR + 2).Formula = "=SUM(L2:L" & LR & ")"

I hope you can see a solution using a loop. 希望您可以看到使用循环的解决方案。 Thank you. 谢谢。

No need to loop at all here for this: 为此,这里根本不需要循环:

Dim LR                    As Long
Dim sLastCol              As String

' change this as needed
sLastCol = "L"

LR = Range("I" & Rows.Count).End(xlUp).Row

Range("I1", Cells(LR, sLastCol)).Interior.Color = RGB(217, 217, 217)
Range("I" & LR + 2, sLastCol & LR + 2).FormulaR1C1 = "=SUM(R2C:R[-2]C)"

or if you can determine the last column using the last populated cell in row 1, you could use: 或者,如果您可以使用第1行中最后一个填充的单元格确定最后一列,则可以使用:

Dim LR                    As Long
Dim lLastCol              As Long

LR = Range("I" & Rows.Count).End(xlUp).Row
lLastCol = Cells(1, Columns.Count).end(xltoleft).column

Range("I1", Cells(LR, lLastCol)).Interior.Color = RGB(217, 217, 217)
Range("I" & LR + 2, Cells(LR + 2, lLastCol)).FormulaR1C1 = "=SUM(R2C:R[-2]C)"

I use a do while loop through the rows count. 我使用do while循环遍历行数。

    lRow = 1

    'Loop through and record what is in the first column
    Do While lRow <= LR.Rows.count

        'Do you code here.

        lRow = lRow + 1
        Range("A" & lRow).Activate
    Loop

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM