Excel VBA: как форматировать каждую вторую строку

Чтобы отформатировать каждую вторую строку в Excel с помощью VBA, вы можете использовать разные подходы. Вот несколько методов с примерами кода:

  1. Использование цикла For:

    Sub FormatEveryOtherRow()
    Dim lastRow As Long
    Dim i As Long
    
    lastRow = Cells(Rows.Count, 1).End(xlUp).Row ' Find the last row in column A
    
    For i = 2 To lastRow Step 2 ' Start from the second row and increment by 2
        Rows(i).Interior.Color = RGB(200, 200, 200) ' Apply formatting to every other row
    Next i
    End Sub
  2. Использование условного форматирования:

    Sub FormatEveryOtherRow()
    Range("A2:A" & Cells(Rows.Count, 1).End(xlUp).Row).Select ' Select the range to apply conditional formatting
    
    ' Define the conditional formatting rule
    Selection.FormatConditions.Add Type:=xlExpression, Formula1:="=MOD(ROW(),2)=0"
    Selection.FormatConditions(Selection.FormatConditions.Count).SetFirstPriority
    Selection.FormatConditions(1).Interior.Color = RGB(200, 200, 200) ' Apply formatting to every other row
    End Sub
  3. Использование автофильтра и смещения:

    Sub FormatEveryOtherRow()
    Dim lastRow As Long
    
    lastRow = Cells(Rows.Count, 1).End(xlUp).Row ' Find the last row in column A
    
    Range("A1").AutoFilter 1, "<>" ' Filter out all rows
    
    ' Apply formatting to every other visible row
    For Each cell In Range("A2:A" & lastRow).SpecialCells(xlCellTypeVisible)
        cell.Offset(, 1).Interior.Color = RGB(200, 200, 200)
    Next cell
    
    ActiveSheet.AutoFilterMode = False ' Turn off the filter
    End Sub

Эти методы позволяют форматировать каждую вторую строку в Excel с помощью VBA. Выберите тот, который лучше всего соответствует вашим потребностям и предпочтениям.