【发布时间】:2020-02-12 16:57:09
【问题描述】:
如何在 Excel 的颜色选择器中更改当前颜色?我用谷歌搜索,完全不知道如何做到这一点。我看过这个Application.Dialogs(xlDialogEditColor),但这不是我想要的。
基本上,当我运行我的宏时,它会将颜色选择器(字体和填充颜色选择器)中的颜色设置为指定的颜色。例如,如果指定的颜色是红色,那么将会发生这种情况
任何帮助将不胜感激,谢谢
【问题讨论】:
如何在 Excel 的颜色选择器中更改当前颜色?我用谷歌搜索,完全不知道如何做到这一点。我看过这个Application.Dialogs(xlDialogEditColor),但这不是我想要的。
基本上,当我运行我的宏时,它会将颜色选择器(字体和填充颜色选择器)中的颜色设置为指定的颜色。例如,如果指定的颜色是红色,那么将会发生这种情况
任何帮助将不胜感激,谢谢
【问题讨论】:
电子表格大师的This article 可以帮助您实现这一目标。写这篇文章的目的是为了在调色板的最近颜色部分添加多种颜色,但您可以轻松地将该方法用于单一颜色(通过在下面的代码中编辑数组以仅包含一个 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
【讨论】: