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 :(您可以使用索引来replaceExcel地址)
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对象时,也可以replaceselect
。 性能明智,它有帮助。
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: eg 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)
- string操作:
码
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