如何在Excel VBA中循环列?

时间:2013-08-12 04:41:56

标签: excel vba

我想循环遍历第一行的每一列,如果在列标题中找到Job,那么我需要循环遍历该列的每个单元格,如果单元格值小于5,则为整行着色。这就是我想要的但是失败:

Sub rr()
Dim a, i, col As Integer
Dim r As Range

r = ActiveSheet.Cells(1, Columns.Count).End(xlToLeft).Column
a = ActiveSheet.Cells(Rows.Count, 1).End(xlUp).Row

For i = 2 To a Step 1
For col = 1 To r Step 1

If Cells(1, col).Value = "job" Then Cells(1 + 1, col).Activate
For Each cell In r

    If r.Value <= 5 Then ActiveSheet.Range(Cells(2, 1), Cells(2, r)).Interior.ColorIndex = 38 Else: Selection.Offset(1, 0).Selection

Next c

Next col

Next i

1 个答案:

答案 0 :(得分:0)

我不确定为什么你不会只使用条件格式,但如果它必须是VBA,也许是这样的?

Sub tgr()

    Dim rngFound As Range
    Dim rngColor As Range
    Dim strFirst As String

    ActiveSheet.AutoFilterMode = False
    Set rngFound = Rows(1).Find("Job", Cells(1, Columns.Count), xlValues, xlWhole)
    If Not rngFound Is Nothing Then
        Cells.Interior.Color = xlNone
        With Intersect(ActiveSheet.UsedRange, Columns(rngFound.Column))
            .AutoFilter 1, "<=5"
            On Error Resume Next
            Set rngColor = .Offset(1).Resize(.Rows.Count - 1).SpecialCells(xlCellTypeVisible)
            On Error GoTo 0
            If Not rngColor Is Nothing Then rngColor.EntireRow.Interior.ColorIndex = 38
            .AutoFilter
        End With
    Else
        MsgBox "No column with heading ""Job"" exists in this worksheet.", , "Exiting macro"
    End If

    Set rngFound = Nothing
    Set rngColor = Nothing

End Sub