IT

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

lottoking 2020. 8. 11. 07:39
반응형

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에서 데이터를 조작하는 매우 강력한 방법입니다.


루프에서는 항상 다음과 같이 R1C1 참조 메소드 를 사용하여 클래스 를 사용하는 것을 선호합니다 .Cells

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

반응형