如何更改 Excel 颜色选择器中的当前颜色?我用谷歌搜索过,完全不知道该怎么做。我见过这个 Application.Dialogs(xlDialogEditColor)
但这不是我想要的。
基本上,当我运行宏时,它会将颜色选择器(字体和填充颜色选择器)中的颜色设置为指定的颜色。例如,如果指定的颜色是红色,那么就会发生这种情况
如有任何帮助,我们将不胜感激,谢谢
最佳答案
This article The Spreadsheet Guru 的作者可以帮助您实现这一目标。本文是为了防止您想要向调色板的最新颜色部分添加多种颜色而编写的,但您可以轻松地对单一颜色使用该方法(通过编辑下面代码中的数组以仅包含一种 RGB 颜色代码)并且这将导致该颜色成为用户选择的颜色。
文章中建议的代码如下:
'Declare Sleep() API #If VBA7 Then ' Excel 2010 or later Public Declare PtrSafe Sub Sleep Lib "kernel32" (ByVal Milliseconds As LongPtr) #Else ' Excel 2007 or earlier Public Declare Sub Sleep Lib "kernel32" (ByVal Milliseconds As Long) #End If Sub LoadRecentColors() 'PURPOSE: Use A List Of RGB Codes To Load Colors Into Recent Colors Section of Color Palette 'SOURCE: www.TheSpreadsheetGuru.com/the-code-vault Dim ColorList As Variant Dim CurrentFill As Variant 'Array List of RGB Color Codes to Add To Recent Colors Section (Max 10) ColorList = Array("066,174,093", "184,055,038", "046,062,081", "056,160,133") 'Store ActiveCell's Fill Color (if applicable) If ActiveCell.Interior.ColorIndex <> xlNone Then CurrentFill = ActiveCell.Interior.Color 'Optimize Code Application.ScreenUpdating = False 'Loop Through List Of RGB Codes And Add To Recent Colors For x = LBound(ColorList) To UBound(ColorList) ActiveCell.Interior.Color = RGB(Left(ColorList(x), 3), Mid(ColorList(x), 5, 3), Right(ColorList(x), 3)) DoEvents SendKeys "%h" Sleep 500 'Pause half-second (units in milliseconds) SendKeys "h" Sleep 500 'Pause half-second (units in milliseconds) SendKeys "m" Sleep 500 'Pause half-second (units in milliseconds) SendKeys "~" Sleep 500 'Pause half-second (units in milliseconds) DoEvents Next x 'Return ActiveCell Original Fill Color If CurrentFill = Empty Then ActiveCell.Interior.ColorIndex = xlNone Else ActiveCell.Interior.Color = currentColor End If End Sub
但是,我建议始终将 SendKeys 方法的 wait
参数设置为 true
,以便让 VBA 知道它必须等待按键按下在继续之前进行处理(例如 SendKeys "%h", True
)。它将增加您的按键被正确注册和执行的可能性。
我不确定,但由于整个过程在 Excel 中运行,并且不涉及其他应用程序,因此甚至可能不需要在每次按键后使用 Sleep
功能,但是对 SendKeys 方法过于谨慎绝不是一个坏主意。
所以,这适用于填充工具。现在,对于字体颜色,快捷键应该是 Alt+H,FC,M
关于Excel VBA - 更改颜色选择器中的当前颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58404357/