Excel 2010 VBA代码未运行

时间:2017-05-22 17:41:13

标签: excel vba excel-vba excel-2010

我目前正在使用Excel 2010,并且正在尝试运行我在VBA for Applications中放置的一些代码(在点击alt + F11之后)。我在双击我想要处理的项目后出现的记事本中输入了代码。我还将所有内容保存为Excel Macro Enabled Workbook(* .xlsm)。

如果列S,T和U符合条件,我试图将列D的背景颜色为绿色或红色。如果列的值均为0,则单元格D应为绿色。如果没有,它应该是红色的。

swing

代码运行并且不会抛出任何错误,但它也没有做任何事情。我做错了什么?

4 个答案:

答案 0 :(得分:2)

您正在错误地使用For循环中的计数器。它应该是这样的......

For i = 2 To 27293

答案 1 :(得分:1)

更改了For condition。 试试这个: -

Sub GreenOrRed()
  Dim i As Integer
  For i = 2 To 27293
    If (Cells(i, "S").Value = 0 And Cells(i, "T").Value = 0 And Cells(i, "U").Value = 0) Then
        Cells(i, "D").Interior.ColorIndex = 10
    Else
        Cells(i, "D").Interior.ColorIndex = 9
    End If
   Next i
End Sub

答案 2 :(得分:1)

略有不同的方法:

Sub GreenOrRed()
    Dim r As Range, rr As Range
    Set rr = Range("D1:D27293")

    For Each r In rr
        If r.Offset(0, 15).Value = 0 And r.Offset(0, 16).Value = 0 And r.Offset(0, 17).Value = 0 Then
            r.Interior.ColorIndex = 10
        Else
            r.Interior.ColorIndex = 9
        End If
    Next r
End Sub

答案 3 :(得分:0)

您可以考虑设置一个(或两个)条件格式规则。

Option Explicit

Sub GreenOrRed()
    With ActiveSheet
        With .Range(.Cells(2, "D"), .Cells(.Rows.Count, "D").End(xlUp))
            .Interior.ColorIndex = 9
            .FormatConditions.Delete
            With .FormatConditions.Add(Type:=xlExpression, Formula1:="=and(sum($S2)=0, sum($T2)=0, sum($U2)=0)")
                .Interior.ColorIndex = 10
                .StopIfTrue = True
            End With
        End With
    End With
End Sub

我使用了单独的SUM函数来确保任何文本返回零值的数值。

Alternate AutoFilter方法。

Sub GreenOrRedFiltered()
    With ActiveSheet
        If .AutoFilterMode Then .AutoFilterMode = False
        With .Range(.Cells(1, "D"), .Cells(.Rows.Count, "D").End(xlUp)).Resize(, 18)
            .Resize(.Rows.Count - 1, .Columns.Count).Offset(1, 0).Columns(1).Interior.ColorIndex = 9
            .AutoFilter Field:=16, Criteria1:=0, Operator:=xlOr, Criteria2:=vbNullString
            .AutoFilter Field:=17, Criteria1:=0, Operator:=xlOr, Criteria2:=vbNullString
            .AutoFilter Field:=18, Criteria1:=0, Operator:=xlOr, Criteria2:=vbNullString
            With .Resize(.Rows.Count - 1, .Columns.Count).Offset(1, 0)
                If CBool(Application.Subtotal(103, .Cells)) Then
                    .Columns(1).SpecialCells(xlCellTypeVisible).Interior.ColorIndex = 10
                End If
            End With
        End With
        If .AutoFilterMode Then .AutoFilterMode = False
    End With
End Sub