列上的Excel VBA循环

时间:2012-12-21 06:03:44

标签: excel vba 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”等等

有什么可以帮助吗?

4 个答案:

答案 0 :(得分:24)

是的,我们以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), "$", "")

e.g。你想得到第27列 - > AA,你可以这样得到它

答案 1 :(得分:7)

尝试的另一种方法。 将初始列设置为Range对象时,也可以替换select。表现明智有帮助。

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 

答案 2 :(得分:1)

如果你想坚持使用相同类型的循环,那么这将起作用:

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

答案 3 :(得分:0)

只需使用Cells函数并通过列循环即可。 单元格(行,列)