18

当我们要在行中循环时,我们可以使用如下代码:

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

4 回答 4

30

是的,让我们Select作为一个例子

示例代码: Columns("A").select

如何循环遍历列:

方法一:(可以用index代替Excel地址)

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

方法二:(使用地址)

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

编辑:剥离 OP 的列

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

例如你想得到第 27 列 --> AA,你可以这样得到

于 2012-12-21T06:31:33.010 回答
10

另一种尝试的方法。当您将初始列设置为 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 
于 2012-12-21T08:40:49.887 回答
3

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

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
于 2012-12-21T08:04:57.640 回答
0

只需使用 Cells 函数并循环遍历列。单元格(行、列)

于 2020-10-29T14:19:56.913 回答