使用命令按钮更改单元格的颜色(VBA Excel)

时间:2016-08-31 11:51:28

标签: excel vba excel-vba macros userform

我目前有一个用户窗体加载三个命令按钮(主要,次要和第三)。这里的想法是用户将使用这三个按钮选择自己的配色方案。

我的工作簿中有代表每种颜色的单元格,然后是一个宏,它在运行时将所有图表对象设置为这些颜色(使用单元格)。

我已设法初始化用户窗体,以便三个命令按钮的内部颜色由我的工作簿中的三个单元格决定:

Private Sub UserForm_Initialize()

Dim cs As Worksheet
Set cs = Sheets("ColourScheme")

TextBox1.SetFocus '' Shift focus away from primary

Primary.BackColor = cs.Range("B1").Interior.color
Secondary.BackColor = cs.Range("B2").Interior.color
Tertiary.BackColor = cs.Range("B3").Interior.color

End Sub

我现在要做的是,当点击每个按钮时,调色板加载,用户使用滚轮或RGB图选择颜色,然后最后选择工作簿中的单元格和命令按钮内部颜色根据用户的选择进行更改。

我不知道是否可以这样做但是到目前为止我没有运气,我试图加载调色板:

Private Sub Primary_Click()

Application.Dialogs.Item(xlDialogColorPalette).Show

End Sub

2 个答案:

答案 0 :(得分:2)

尝试我在多个应用程序中使用的功能,它稍微转换为适合您原来的最小化代码,让我知道它是否适合您...

Private Sub Primary_Click()

Const ColorIndexLast                As Long = 32       'index of last custom color in palette
Dim PickNewColor                    As Double          'color that was picked in the dialogue
Dim myOrgColor                      As Double          'original color of color index 32

'save original palette color,modify Range according to your needs
myOrgColor = Range("A1").Interior.Color

'call the color picker dialogue
If Application.Dialogs(xlDialogEditColor).Show(ColorIndexLast) = True Then

    ' "OK" was pressed, read the new color from the palette
    PickNewColor = ActiveWorkbook.Colors(ColorIndexLast)
    ActiveWorkbook.Colors(ColorIndexLast) = myOrgColor  ' reset palette color to its original value
Else
    ' "Cancel" was pressed, palette wasn't changed >> return old color (or xlNone if no color was passed to the function)
    PickNewColor = myOrgColor
End If

' update Colors in relevant Cell
Range("A1").Interior.Color = PickNewColor

End Sub

答案 1 :(得分:0)

这是我到达的解决方案:

Private Sub Primary_Click()

Dim cs As Worksheet
Set cs = Sheets("ColourScheme")

Dim newColour As Long

Application.Dialogs(xlDialogEditColor).Show (1)

newColour = ThisWorkbook.Colors(1)

cs.Range("B1").Interior.color = newColour

Primary.BackColor = newColour

End Sub