2015-06-04 245 views
1

我需要突出显示每行中超过列AU中数值的单元格;那么为下一行做这个工作,但是我无法获得列AU的值是迭代的,意味着改变到下一行的值。VBA迭代循环

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

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 
+0

原谅我,如果这是一个noob问题,但我不使用范围()那么多(我总是直接在细胞上循环),但什么是“AUn”?那只是一个包含零的未定义变量? –

+1

这是你正在尝试? '如果myRange.Cells(i,j).Value

+0

AUn是我尝试调用列作为一个排序数组,允许我循环的值n变化好像我使用函数(= $ AU11,而不是= $ AU $ 11) – gduhoffmann

回答

1
  1. 你有1个循环额外
  2. AUn被当作空变量。我想你想在Col AU的相关行中工作。

这是你正在尝试? (未经测试

我评论的代码,以便让我知道,如果你还有任何疑问:)

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 
+0

好了试过这个代码,它似乎没有识别AU中的值(该值源于公式(= AQ +(AR * 2)) )会导致单元格引用为零? – gduhoffmann

+0

您是否使用'.Range(“AU”&n).Value'而不是'Range(“AU”&n).Value'?注意Range对象之前的DOT? –

+0

谢谢,无视最后的评论,因为我在引用AU时应该使用AT再次感谢完美的代码! – gduhoffmann