[英]Excel VBA Loop on columns
當我們要在行中進行循環時,我們可以使用如下代碼:
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
如何遍歷列:
方法一:(可以用索引代替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,你可以這樣得到
另一種方法可以嘗試。 當您將初始列設置為 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
如果您想堅持使用相同類型的循環,那么這將起作用:
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
只需使用 Cells 函數並循環遍歷列即可。 單元格(行,列)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.