[英]VBA loop through range, by columns first
他們有什么方法可以循環遍歷可以首先循環列的范圍(最好是 X 中的每個單元格)? 例如 A1、A2、A3、A4 而不是 A1、B1、C1、D1
我試着調換范圍,但可惜這不起作用
For Each cell In application.transpose(.Range("C3:G100"))
我有一種感覺,我將不得不使用類似的東西
for c = 0 to .Range("C3:G100").columns.count
for r =0 to .range("C3:G100").rows.count
dim ws as worksheet
set ws = ActiveSheet ' change here as required
For icol = 1 to n '(change here to max)
For irow = 1 to n '(change here to max)
'some code here
' access cells as ws.cells(irow, icol)
nex irow
next icol
把它放在一個數組中。
Dim i As Long, j As Long
Dim avArray As Variant
avArray = Range("C3:G100").Value
For j = LBound(avArray, 2) To UBound(avArray, 2)
For i = LBound(avArray, 1) To UBound(avArray, 1)
avArray(i, j) = CStr(avArray(i, j)) 'do something here, this
'example just makes the
'value a string
Next
Next
如果您要進行更改,則只需在完成后將數組轉儲回工作表
Range("C3:G100").Value = avArray
嘗試這個。 下面的宏將:
(*) 在活動工作表中:
(1) 確定所有非空單元格的范圍,
(2) 逐列循環遍歷該范圍,
(3) 逐個單元地循環遍歷每一列
Sub LoopThruUsedRangeColByCol()
Dim rngCol, rngAll, cell As Range, cnt As Long
Set rngAll = Range("A1").CurrentRegion
'MsgBox R.Address(0, 0), , "All data"
cnt = 0
For Each rngCol In rngAll.Columns
rngCol.Select
For Each cell In Selection
cnt = cnt + 1
Debug.Print (cell.Address)
Debug.Print (cell.row)
Debug.Print (cell.Column)
If cnt > 3 Then End
Next cell
Next rngCol
End Sub
(1) cnt
添加只是為了輸出不會壓倒。 Remove If cnt > 3 Then End
after demo.
(2)需要打開“立即窗口”才能看到debug.print輸出。
為此:菜單欄 => 查看菜單 => 立即窗口
代替
For Each cell In application.transpose(.Range("C3:G100"))
'Your Code here
Next cell
和
Dim col As Range
For Each col In Range("C3:G100").Columns
For Each cell In col.Cells
'Your Code here
Next cell
Next col
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.