如何使用Excel VBA宏循环行?

Jef*_*eff 11 excel vba loops excel-vba

我是VBA的新手,但对PHP非常好.话虽这么说,我正在努力与VBA循环......

我有40行称为"SH1"的这张表:

SH1

     A     B     C     D     E
 1   2   One    1.0a   12
 2   7   Two    2.0b   34
 3  13   Three  3.0c   56
 4  14   Four   4.0d   78
..
40
Run Code Online (Sandbox Code Playgroud)

我需要遍历40行并检查A列中的值.如果A列中的值符合我的条件(见下文),则生成一些输出并将其放入另一张表中.

我的输出表是3列,称为"SH2":

SH2

     A     B     C     D     E
 1  1.0a   12    One
    2.0b   34    Two
 2  3.0c   56    Three
    4.0d   78    Four
..
15
Run Code Online (Sandbox Code Playgroud)

我决定什么去哪里的标准:

// First loop:
if a1 < 8, put c1 in SH2 a1, put d1 in SH2 b1, put b1 in SH2 c1
if a2 < 8, put c2 in SH2 a1, put d2 in SH2 b1, put b2 in SH2 c1
// ... loop through a40 ...
Run Code Online (Sandbox Code Playgroud)

然后:

// Second loop:
if a1 > 8 AND a1 < 16, put c1 in SH2 a2, put d1 in SH2 b2, put b1 in SH2 c2
if a2 > 8 AND a2 < 16, put c2 in SH2 a2, put d2 in SH2 b2, put b2 in SH2 c2
// ... loop through a40 ...
Run Code Online (Sandbox Code Playgroud)

进展编辑:

似乎工作,但想知道是否有"更清洁"的方式?

Sub CatchersPick2()
    Dim curCell As Range

    For Each curCell In Sheet4.Range("C3:C40").Cells
        If curCell.Value > 0 And curCell.Value < 73 Then
            cLeft = cLeft _
                & curCell.Offset(0, 5) & "." _
                & curCell.Offset(0, 6) & vbLf
            cMidl = cMidl _
                & curCell.Offset(0, -2) & ", " _
                & curCell.Offset(0, -1) & " " _
                & curCell.Offset(0, 7) & vbLf
            cRght = cRght _
                & curCell.Offset(0, 9) & " " _
                & curCell.Offset(0, 2) & " " _
                & curCell.Offset(0, 11) & " " _
                & curCell.Offset(0, 10) & vbLf
        End If
    Next curCell

    Sheet6.Range("B3") = cLeft
    Sheet6.Range("C3") = cMidl
    Sheet6.Range("D3") = cRght
    Sheet6.Range("B3:D3").Rows.AutoFit
    Sheet6.Range("B3:D3").Columns.AutoFit

End Sub
Run Code Online (Sandbox Code Playgroud)

jsw*_*f19 11

Dim cell As Range
For Each cell In Range("a1:a40")
    'do stuff here
Next cell
Run Code Online (Sandbox Code Playgroud)

您可以获取当前行cell.Row.祝你好运^ _ ^