The color of every second row in the table

I have a table with some merged cells, and I would like to color every second row, starting from the first, using VBA code.

Here is how I tried:

Sub test()
    Dim Zeile As Long
    With Tabelle2
        For Zeile = 1 To .UsedRange(Rows.Count).End(xlUp).Row Step 2
         .Range(.Cells(Zeile, 1),.Cells(Zeile,8)).Interior.ColorIndex= 15
        Next
    End With
End Sub

The table looks like this:

enter image description here

And it should look like this:

enter image description here

Thank you in advance!

+4
source share
2 answers

I believe that you are looking for something like this.

We are adding a boolean flag so that we can use it ( cf).

We can Resize MergeAreainstead of the cell value itself.

If there are merged cells, this allows for this area - if not, it will not.

Then add the potential counter MergeAreato our row counter ( Zeile).

Sub ColorEveryOther()
Dim cf As Boolean
Dim Zeile As Long
Dim lr As Long
lr = ActiveSheet.UsedRange.Rows.CountLarge
For Zeile = 1 To lr
    If Not cf Then Range("A" & Zeile).MergeArea.Resize(, 8).Interior.ColorIndex = 15
    Zeile = (Zeile + Range("A" & Zeile).MergeArea.Cells.CountLarge) - 1
    cf = Not cf
Next Zeile
End Sub

Results:

results

EDIT:

This is your code updated.

I also cleared the previous code a bit.

Sub test()
    Dim Zeile As Long
    Dim cf As Boolean
    With Tabelle2
        For Zeile = 1 To .UsedRange(Rows.Count).End(xlUp).Row
            If cf = False Then .Cells(Zeile, 1).MergeArea.Resize(, 8).Interior.ColorIndex = 15
            Zeile = (Zeile + .Cells(Zeile, 1).MergeArea.Cells.CountLarge) - 1
            cf = Not cf
        Next
    End With
End Sub

:

cf = Not cf - :

If cf = True Then
    cf = False
Else
    cf = True
End If

cf = False .

cf = Not False= True

cf = Not True= False

, :)

, MOD , .

+5
Dim Zeile As Double
Dim WhiteColor As Boolean
WhiteColor = False

Dim RangeSize As Byte

Range("A1").Select
Selection.SpecialCells(xlCellTypeLastCell).Select
Zeile = ActiveCell.Row

Range("A1").Select

Do Until ActiveCell.Row = Zeile + 1
    RangeSize = Selection.Count

    If WhiteColor = False Then
        Range(Cells(ActiveCell.Row, 1), Cells(ActiveCell.Row + RangeSize - 1, 8)).Interior.Color = RGB(191, 191, 191)
        WhiteColor = True
    Else
        Range(Cells(ActiveCell.Row, 1), Cells(ActiveCell.Row + RangeSize - 1, 8)).Interior.Color = vbWhite
        WhiteColor = False
    End If
    ActiveCell.Offset(1, 0).Select
Loop

, :

enter image description here

+2

Source: https://habr.com/ru/post/1692053/


All Articles