programing

열의 Excel VBA 루프

showcode 2023. 4. 15. 09:42
반응형

열의 Excel VBA 루프

행내에서 루프를 실행하는 경우는, 다음과 같은 코드를 사용할 수 있습니다.

i = 1
Do
   Range("E" & i & ":D" & i).Select
   i = i + 1
Loop Until i > 10

기둥에 루프를 그리려면 어떻게 해야 할까요?

위와 같은 방법을 사용할 수 있습니까?

Excel의 열은 A, B, C, ..., Y, Z, AA, AB, AC 등과 같은 복합체이지만, "Z"에서 "AA"까지의 루프 사이에 문제가 발생합니다.

알파벳 열을 "A"에서 "Z"로 루프한 다음 "AA", "AB" 등으로 계속하는 방법

도와줄 수 있는 게 있나요?

네, 사용하겠습니다.Select예로서

샘플 코드:Columns("A").select

열을 루프하는 방법:

방법 1: (인덱스를 사용하여 Excel 주소를 바꿀 수 있습니다.)

For i = 1 to 100
    Columns(i).Select
next i

방법 2: (주소 사용)

For i = 1 To 100
 Columns(Columns(i).Address).Select
Next i

편집: OP를 위해 컬럼을 제거합니다.

columnString = Replace(Split(Columns(27).Address, ":")(0), "$", "")

예를 들어, 27번째 열을 얻고 싶다면 --> AA, 이 방법으로 얻을 수 있습니다.

또 다른 시험방법입니다.또한.select첫 번째 열을 Range 개체로 설정할 때 대체할 수 있습니다.퍼포먼스 면에서도 도움이 됩니다.

Dim rng as Range

Set rng = WorkSheets(1).Range("A1") '-- you may change the sheet name according to yours.

'-- here is your loop
i = 1
Do
   '-- do something: e.g. show the address of the column that you are currently in
   Msgbox rng.offset(0,i).Address 
   i = i + 1
Loop Until i > 10

** 열 번호를 사용하여 열 이름을 가져오는 두 가지 방법**

  • 분할()

코드

colName = Split(Range.Offset(0,i).Address, "$")(1)
  • 문자열 조작:

코드

Function myColName(colNum as Long) as String
    myColName = Left(Range(0, colNum).Address(False, False), _ 
    1 - (colNum > 10)) 
End Function 

같은 종류의 루프를 사용하는 경우는, 다음과 같이 동작합니다.

Option Explicit

Sub selectColumns()

Dim topSelection As Integer
Dim endSelection As Integer
topSelection = 2
endSelection = 10

Dim columnSelected As Integer
columnSelected = 1
Do
   With Excel.ThisWorkbook.ActiveSheet
        .Range(.Cells(columnSelected, columnSelected), .Cells(endSelection, columnSelected)).Select
   End With
   columnSelected = columnSelected + 1
Loop Until columnSelected > 10

End Sub

편집

실제로 스프레드시트 영역의 모든 셀을 루프하고 싶다면 다음과 같은 방법을 사용하십시오.

Sub loopThroughCells()

'=============
'this is the starting point
Dim rwMin As Integer
Dim colMin As Integer
rwMin = 2
colMin = 2
'=============

'=============
'this is the ending point
Dim rwMax As Integer
Dim colMax As Integer
rwMax = 10
colMax = 5
'=============

'=============
'iterator
Dim rwIndex As Integer
Dim colIndex As Integer
'=============

For rwIndex = rwMin To rwMax
        For colIndex = colMin To colMax
            Cells(rwIndex, colIndex).Select
        Next colIndex
Next rwIndex

End Sub

Cells 함수를 사용하고 열을 반복하기만 하면 됩니다.셀(행, 열)

언급URL : https://stackoverflow.com/questions/13985060/excel-vba-loop-on-columns

반응형