簡體   English   中英

如何在Excel VBA中的范圍內循環列

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

標題可能與其他問題類似,但據我所知,沒有人問過這個問題。 我試圖遍歷所有列,並將它們的總和添加到最后一行之后的底部,並在總和之前添加值。 到現在為止,我一直在寫出每個列的名稱,但是工作表越來越大,這正浪費時間,因為我知道必須有更好的方法。 請記住,我是VBA的新手。 代碼部分是:

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 & ")"

希望您可以看到使用循環的解決方案。 謝謝。

為此,這里根本不需要循環:

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)"

或者,如果您可以使用第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)"

我使用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