VBA首先按列循环遍历范围

时间:2015-07-03 10:49:23

标签: vba excel-vba excel

他们是否可以循环遍历一个范围(理想情况下是X中的每个单元格)可以先循环列?例如A1,A2,A3,A4而不是A1,B1,C1,D1

我尝试过移调范围,但唉这不起作用

config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html"));

我有一种感觉,我将不得不使用像

这样的东西
For Each cell In application.transpose(.Range("C3:G100"))

4 个答案:

答案 0 :(得分:2)

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

答案 1 :(得分:0)

把它放在一个数组中。

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

答案 2 :(得分:0)

尝试一下。下面的宏将:
(*)在活动工作表中:
(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,以使输出不会淹没。演示后删除If cnt > 3 Then End

(2)您需要打开“立即窗口”以查看debug.print输出。
为此:菜单栏=>视图菜单=>立即窗口

答案 3 :(得分:0)

替换

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