Excel VBA Loop on columns

前端 未结 4 1609
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-14 03:12

when we are going to do a loop in the rows, we can use code like the following:

i = 1
Do
   Range(\"E\" & i & \":D\" & i).Select
   i = i + 1
Loo         


        
4条回答
  •  情深已故
    2020-12-14 03:39

    Another method to try out. Also select could be replaced when you set the initial column into a Range object. Performance wise it helps.

    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
    

    ** Two methods to get the column name using column number**

    • Split()

    code

    colName = Split(Range.Offset(0,i).Address, "$")(1)
    
    • String manipulation:

    code

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

提交回复
热议问题