Цвета альтернативных рядов в диапазоне - PullRequest
9 голосов
/ 07 января 2011

Я предложил следующее, чтобы чередовать цвета строк в указанном диапазоне:

Sub AlternateRowColors()
Dim lastRow as Long

lastRow = Range("A1").End(xlDown).Row

For Each Cell In Range("A1:A" & lastRow) ''change range accordingly
    If Cell.Row Mod 2 = 1 Then ''highlights row 2,4,6 etc|= 0 highlights 1,3,5
        Cell.Interior.ColorIndex = 15 ''color to preference
    Else
        Cell.Interior.ColorIndex = xlNone ''color to preference or remove
    End If
Next Cell

End Sub

Это работает, но есть ли более простой метод?

Следующие строки кода могут быть удалены, если ваши данные не содержат существующих цветов:

    Else
        Cell.Interior.ColorIndex = xlNone

Ответы [ 8 ]

8 голосов
/ 11 апреля 2013

Мне нужно делать это часто, и мне хотелось бы иметь возможность легко изменять цвета, которые я использую для создания полос. Следующая подпрограмма делает это очень просто:

Sub GreenBarMe(rng As Range, firstColor As Long, secondColor As Long)
    rng.Interior.ColorIndex = xlNone
    rng.FormatConditions.Add Type:=xlExpression, Formula1:="=MOD(ROW(),2)=0"
    rng.FormatConditions(1).Interior.Color = firstColor
    rng.FormatConditions.Add Type:=xlExpression, Formula1:="=MOD(ROW(),2)<>0"
    rng.FormatConditions(2).Interior.Color = secondColor
End Sub

Использование:

Sub TestGreenBarFormatting()
    Dim rng As Range
    Dim firstColor As Long
    Dim secondColor As Long

    Set rng = Range("A1:D12")
    firstColor = vbGreen
    secondColor = vbYellow

    Call GreenBarMe(rng, firstColor, secondColor)
End Sub
7 голосов
/ 07 января 2011

Цвета чередующихся строк можно сделать с помощью условного форматирования:

screen capture

4 голосов
/ 05 апреля 2011

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

Sub Color_Alt_Rows(Rng As Range)
    Application.ScreenUpdating = False

    Rng.Interior.ColorIndex = xlNone
    Rng = Rng.SpecialCells(xlCellTypeVisible)
    Rng.FormatConditions.Add Type:=xlExpression, Formula1:="=mod(row()+1,2)"
    Rng.FormatConditions(1).Interior.ColorIndex = 34
End Sub

Попробуйте с помощью Color_Alt_Rows Range("a2:d5")

2 голосов
/ 31 июля 2016

Мое решение

Подпрограмма, назначаемая кнопке или некоторому коду

Public Sub Band_Goals()
    'Just pass the start and end rows
    'You will have to update the function to select the
    'the correct columns

    BandRows_Invisble 12, 144

End Sub

Функция

Private Sub BandRows_Invisble(StartRow As Integer, EndRow As Integer)

    Dim i As Long, nothidden As Boolean


    Application.ScreenUpdating = False
    Application.Calculation = xlCalculationManual

    Range("A" & StartRow & ":K" & EndRow).Interior.ColorIndex = xlNone

    For i = StartRow To EndRow
        If Not Rows(i).Hidden Then
            nothidden = nothidden + 1
            If Not nothidden Then
                    'Download this app to help with color picking
                    'http://www.iconico.com/download.aspx?app=ColorPic
                    Range("A" & i & ":K" & i).Interior.Color = RGB(196, 189, 151)

            End If
        End If
    Next i

    Application.Calculation = xlCalculationAutomatic
    Application.ScreenUpdating = True

End Sub
1 голос
/ 19 апреля 2013
'--- Alternate Row color, only non-hidden rows count

Sub Test()

Dim iNumOfRows As Integer, iStartFromRow As Integer, iCount As Integer
iNumOfRows = Range("D61").End(xlDown).Row '--- counts Rows down starting from D61

For iStartFromRow = 61 To iNumOfRows

    If Rows(iStartFromRow).Hidden = False Then '--- only non-hidden rows matter

        iCount = iCount + 1

        If iCount - 2 * Int(iCount / 2) = 0 Then
            Rows(iStartFromRow).Interior.Color = RGB(220, 230, 241)
        Else
            Rows(iStartFromRow).Interior.Color = RGB(184, 204, 228)
        End If

    End If
Next iStartFromRow

End Sub
0 голосов
/ 18 января 2019

установить их инициализированные где-то:

Dim arr_Lng_Row_Color(1) As Long
arr_Lng_Row_Color(0) = RGB(int_Color_1_R, int_Color_1_G, int_Color_1_B)
arr_Lng_Row_Color(1) = RGB(int_Color_2_R, int_Color_2_G, int_Color_2_B)

В любой строке вы хотите, чтобы это установило цвет

ws_SomeSheet.Rows(int_Target_Row).EntireRow.Interior.Color = arr_Lng_Row_Color(int_Target_Row Mod 2)

0 голосов
/ 05 августа 2015

В моем Excel 2010 есть опция для форматирования в виде таблицы, где вы также можете выбрать диапазон и заголовки.Нет необходимости в сценариях.Excel Table

0 голосов
/ 07 января 2011

Ну, вы можете удалить часть else, так как вы оставите ее в цвете по умолчанию

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...