VBA迭代循环

时间:2015-06-04 17:30:51

标签: excel excel-vba vba

我需要突出显示每行中超过该行数据列AU 中值的单元格;然后为下一行执行此操作,但我无法使列AU的值成为迭代意味着更改为下一行的值。

让我知道我在这里做错了什么。

Sub highlight()
    Application.ScreenUpdating = False

    Dim myRange As Range
    Dim i As Long, j As Long

    Set myRange = Range("F11:AP20")
    For n = 11 To 20
        For i = 1 To myRange.Rows.Count
            For j = 1 To myRange.Columns.Count
                If myRange.Cells(i, j).Value < Range(AUn).Value Then
                    myRange.Cells(i, j).Interior.Color = 65535
                Else
                    myRange.Cells(i, j).Interior.ColorIndex = 2
                End If
            Next j
        Next i
    Next n
End Sub

1 个答案:

答案 0 :(得分:1)

  1. 你有1个额外的循环
  2. AUn被视为空白变量。我想你想在Col AU中使用相关的行。
  3. 这是你在尝试什么? (的未测试

    我已对代码进行了评论,如果您仍有任何疑问,请与我联系:)

    Sub highlight()
        Application.ScreenUpdating = False
    
        Dim myRange As Range
        Dim n As Long, j As Long
        Dim ws As Worksheet
    
        '~~> Change this to the relevant worksheet
        Set ws = ThisWorkbook.Sheets("Sheet1")
    
        With ws
            '~~> Set your range
            Set myRange = .Range("F11:AP20")
    
            '~~> Loop through the rows (11 to 20 in this case)
            For n = myRange.Row To (myRange.Row + myRange.Rows.Count - 1)
                '~~> Loop through the columns (F to AP in this case)
                For j = myRange.Column To (myRange.Column + myRange.Columns.Count - 1)
                    If .Cells(n, j).Value < .Range("AU" & n).Value Then
                        .Cells(n, j).Interior.Color = 65535
                    Else
                        .Cells(n, j).Interior.ColorIndex = 2
                    End If
                Next j
            Next n
        End With
    End Sub