当我们要在行中进行循环时,可以使用以下代码:
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列,可以按照以下方式获取
尝试另一种方法。
同时,当您将初始列设置为Range对象时,select
可以被替换。从性能方面考虑,这会有所帮助。
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
**通过列数获取列名的两种方法**
code
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
Range(colIndex & i & ":" & colIndex & i).Select
"colIndex"是一个变量,用于在Excel中循环列索引。 - wahyueka31如果您想继续使用相同类型的循环,那么以下内容将起作用:
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
Range(colIndex & i & ":" & colIndex & i).Select
“colIndex”是一个变量,用于在Excel中循环列索引。 - wahyueka31.Range(.Cells(i,colIndex),.Cells(i,colIndex))。Select
相同......这就是我在我的建议答案中提供的内容,只是名称更具描述性。但是,在您的评论中,您提到了Range(colIndex&i&:“”&colIndex&i)。Select
......在冒号后不需要重复的部分:Range(colIndex&i)。Select
......实际上等同于.cells(i,colIndex)
。 - whytheq只需使用Cells函数并循环遍历列。 Cells(行,列)
Range(colIndex & i & ":" & colIndex & i).Select
“colIndex”是一个变量,用于在Excel中循环列索引。 - wahyueka31