首页 > 解决方案 > 当值更改VBA时,从调色板中查找colorindex为行着色

问题描述

代码:

Public Sub HighLightRows()
    Dim i As Integer
    i = 2
    Dim c As Integer
    c = 2       'Color 1

    'Dim colorIndex As XlColorIndex: colorIndex = Application.Dialogs(xlDialogEditColor).Show(10)
    'MsgBox colorIndex

    Do While (Cells(i, 1) <> "")
        If (Cells(i, 1) <> Cells(i - 1, 1)) Then 'check for different value in cell A (index=1)
            If c = 2 Then
                c = 24   'color 2
            Else
                c = 2   'color 1
            End If
        End If

        Rows(Trim(Str(i)) + ":" + Trim(Str(i))).Interior.colorIndex = c
        i = i + 1
    Loop
    End Sub

此代码完美运行,并在列中的值更改时更改颜色。但是颜色是在代码中指定的。我希望用户选择他/她选择的颜色。

我用上面的代码得到的输出:我想要代码做什么: 打开调色板。用户选择一种颜色。颜色索引被传递给一个变量。当值更改时,行将交替显示为白色和所选颜色。 例如。如果用户从调色板中选择蓝色,则行将是具有交替组的蓝白色。如果用户从调色板中选择绿色,则行将是具有交替组的绿色和白色。 我尝试包含此代码:
在此处输入图像描述








Dim colorIndex As XlColorIndex: colorIndex = Application.Dialogs(xlDialogEditColor).Show(10)
MsgBox colorIndex

调色板完美打开,但MsgBox colorIndex给我 -1 作为输出。

我似乎无法让它工作。代码有什么变化。?

标签: vbaexcelcolor-palette

解决方案


如果选择了颜色并且用户按下了取消,则Dialogs(xlDialogEditColor)返回。要获得选定的颜色,请使用下面的示例。True = -1False = 0ActiveWorkbook.Colors(10)

Option Explicit

Public Sub ColorPaletteDialogBox()
    Dim lcolor As Long
    If Application.Dialogs(xlDialogEditColor).Show(10) = True Then
      'user pressed OK
      lcolor = ActiveWorkbook.Colors(10)
      ActiveCell.Interior.Color = lcolor
    Else
      'user pressed Cancel
    End If
End Sub

因此,对于您的循环,您可以使用类似...</p>

Option Explicit

Public Sub HighLightRows()
    Dim c As Integer
    c = 2       'Color 1

    Dim i As Long 'integer is too small for row counting!
    i = 2

    If Application.Dialogs(xlDialogEditColor).Show(10) = True Then
        Do While (Cells(i, 1) <> "")
            If (Cells(i, 1) <> Cells(i - 1, 1)) Then 'check for different value in cell A (index=1)
                If c = 2 Then
                    c = 10   'color 2
                Else
                    c = 2   'color 1
                End If
            End If

            Rows(Trim(Str(i)) + ":" + Trim(Str(i))).Interior.colorIndex = c
            i = i + 1
        Loop
    Else
      'user pressed Cancel
    End If
End Sub

推荐阅读