VBA宏具有多个任务

时间:2019-01-02 12:15:53

标签: excel vba excel-vba

我正在处理一个执行以下操作的excel宏: 检查所有值等于或大于9的行 如果所说的行具有所有类似的值,它将以红色突出显示A列中的第一个单元格,并在检查所有行之后将输出突出显示的行数。 到目前为止,我还停留在给出编译器错误的代码上-预期的函数或变量。有人可以协助解决这一问题吗?

Public Sub test()

    S = 0
    j = 1
    A = 0
    For j = 3 To 7 Step 1
        If Cells(i, j) >= 9 Then A = A + 1
        End If
    Next
    If A = 5 Then
        Cells(1, j).Font.Color = RGB(255, 0, 0)
        S = S + 1
    End If
    MsgBox (S)

End Sub

1 个答案:

答案 0 :(得分:0)

下面,我尝试提供尽可能多的细节,以全面解释每个步骤。进行必要的更改,然后尝试以下操作:

Option Explicit
Public Sub test()

    Dim StartRow As Long, StartColumn As Long, LastColumn As Long, Lastrow As Long, i As Long, j As Long, CounterValues As Long, CounterRows As Long

    StartRow = 2 'From which row will start the loop
    StartColumn = 1 'From which column will start the loop
    CounterRows = 0 'Reset Counter

    'Refer to the worksheets you work on
    With ThisWorkbook.Worksheets("Sheet1")

        Lastrow = .Cells(.Rows.Count, "A").End(xlUp).Row 'Find the last row of column A

        'Loop Each Row from StartRow(2) to Lastrow (6)
        For i = StartRow To Lastrow

            LastColumn = .Cells(i, .Columns.Count).End(xlToLeft).Column 'Find the last column of row i

            'Loop Each Column from StartColumn(1) To LastColumn(4)
            CounterValues = 0
            For j = StartColumn To LastColumn

                If .Cells(i, j).Value >= 9 Then
                    CounterValues = CounterValues + 1
                End If

            Next j

            'If all values are equal or greater thant 9
            If CounterValues = LastColumn Then
                'Color first row cell
                .Cells(i, 1).Font.Color = RGB(255, 0, 0)
                'Count color rows
                CounterRows = CounterRows + 1
            End If

        Next i

        MsgBox CounterRows

    End With

End Sub