嵌套If语句进入双循环

时间:2016-01-12 20:41:38

标签: vba excel-vba loops excel

我在使用双循环函数时遇到问题,该函数会交替显示行的格式。

我知道我可以通过条件格式化到范围脚本来做到这一点,但是,当我学习越来越多地使用VBA时,我认为尝试使用双循环是好的。

我没有进一步发展。

Sub AlternateRowColor2()
Dim lastRow As Long

lastRow = Range("A1").End(xlDown).Row

For Each Cell In Range("A1:A" & lastRow) 
    If Cell.Row Mod 2 = 1 Then 
        Cell.Interior.ColorIndex = 43 
    remove
    End If
Next Cell

End Sub

我可以定义循环但是迷失在for函数中以使用下一个

Sub AlternateRowColors()
Dim I As Integer
Dim P As Integer
Dim lastRow As Long

For I = 1 To 2
For P = 1 To 1
lastRow = Range(P).End(xlDown).Row
For Each Column In Range(I, lastRow)

2 个答案:

答案 0 :(得分:1)

您可以使用插入表功能,以便" color"行。它实际上确实更多......

    Sub InsertTable()
    '
    ' InsertTable
    '
    '
        Range("A1:C7").Select
        ActiveSheet.ListObjects.Add(xlSrcRange, Range("$A$1:$C$7"), , xlYes).Name = _
            "Table1"
        Range("Table1[#All]").Select
    End Sub

结果:

InsertTable

所以循环:

    Sub Looping()
    ' Looping Makro
        Dim mySheet As Worksheet
        Dim myCell As Range
        Dim X, Y, X_Off, Y_Off

        X_Off = 5
        Y_Off = 3

        Set mySheet = Application.ActiveSheet

        For X = 1 To 10

            Set myCell = mySheet.Cells(X + X_Off + 1, Y_Off + 1)
            myCell.Interior.ColorIndex = 23
            myCell.FormulaR1C1 = X

            Set myCell = mySheet.Cells(X_Off + 1, X + Y_Off + 1)
                                                 '^ We use here X too
            myCell.Interior.ColorIndex = 23
            myCell.FormulaR1C1 = X

            For Y = 1 To 10

                Set myCell = mySheet.Cells(X + X_Off + 1, Y + Y_Off + 1)
                myCell.FormulaR1C1 = X * Y

                If ((X Mod 2) = 0) Then
                    myCell.Interior.ColorIndex = 43
                End If

            Next Y
        Next X

    End Sub

结果:

Loops]

所以最后你也可以查看那些site1 site2

答案 1 :(得分:0)

我认为这可能就是你要找的东西。您需要显式增加for循环。但你的问题有点不清楚

Sub AlternateRowColors()
    Dim I As Integer
    Dim P As Integer
    Dim lastRow As Long

    For I = 1 To 2
        For P = 1 To 1
            lastRow = Range(P).End(xlDown).Row
            For Each Column In Range(I, lastRow)
        Next P
    Next I