it-source

Excel에서 범위의 각 행을 반복합니다.

criticalcode 2023. 5. 31. 16:03
반응형

Excel에서 범위의 각 행을 반복합니다.

이것은 (과거에 들어본 적이 있을 수도 있지만) 기본 기능이 있는 것 중 하나입니다. 하지만 저는 그것을 기억하기 위해 머리를 긁적이고 있습니다.

Excel VBA를 사용하여 다중 열 범위의 각 행을 순환하려면 어떻게 해야 합니까?제가 검색한 모든 튜토리얼은 1차원 범위를 통해 작업한다는 것만 언급하는 것 같습니다.

Dim a As Range, b As Range

Set a = Selection

For Each b In a.Rows
    MsgBox b.Address
Next

이와 같은 것:

Dim rng As Range
Dim row As Range
Dim cell As Range

Set rng = Range("A1:C2")

For Each row In rng.Rows
  For Each cell in row.Cells
    'Do Something
  Next cell
Next row

우연히 이것을 발견하고 제 해결책을 제안하려고 생각했습니다.저는 일반적으로 다차원 배열에 범위를 할당하는 내장 기능을 사용하는 것을 좋아합니다(제 안에 JS 프로그래머도 있는 것 같습니다).

나는 다음과 같은 코드를 자주 작성합니다.

Sub arrayBuilder()

myarray = Range("A1:D4")

'unlike most VBA Arrays, this array doesn't need to be declared and will be automatically dimensioned

For i = 1 To UBound(myarray)

    For j = 1 To UBound(myarray, 2)

    Debug.Print (myarray(i, j))

    Next j

Next i

End Sub

변수에 범위를 할당하는 것은 VBA에서 데이터를 조작하는 매우 강력한 방법입니다.

루프에서, 나는 항상 사용하는 것을 선호합니다.CellsR1C1 참조 방법을 사용하는 클래스는 다음과 같습니다.

Cells(rr, col).Formula = ...

이를 통해 다양한 셀을 쉽고 빠르게 루프할 수 있습니다.

Dim r As Long
Dim c As Long

c = GetTargetColumn() ' Or you could just set this manually, like: c = 1

With Sheet1 ' <-- You should always qualify a range with a sheet!

    For r = 1 To 10 ' Or 1 To (Ubound(MyListOfStuff) + 1)

        ' Here we're looping over all the cells in rows 1 to 10, in Column "c"
        .Cells(r, c).Value = MyListOfStuff(r)

        '---- or ----

        '...to easily copy from one place to another (even with an offset of rows and columns)
        .Cells(r, c).Value = Sheet2.Cells(r + 3, 17).Value


    Next r

End With

언급URL : https://stackoverflow.com/questions/1463236/loop-through-each-row-of-a-range-in-excel

반응형