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

我目前有一个用户表单加载三个命令button(小学,中学和第三)。 这里的想法是用户将使用这三个button来select他们自己的配色scheme。

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

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

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 

我现在要做的是,当每个button被点击时,调色板加载,用户使用轮或RGB图select一种颜色,然后最终我的工作簿中的单元格和命令button内部颜色更改基于用户的select。

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

 Private Sub Primary_Click() Application.Dialogs.Item(xlDialogColorPalette).Show End Sub 

尝试我在几个应用程序上使用的function,它稍微转换为适合您最初的最小化代码,让我知道它是否适合您…

 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 

这是我到达的解决scheme:

 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