如何使用VBA切换Interior.Color

我想要一个窗体控件button,使用VBA,将select更改为Selection.Interior.Color = RGB(255, 0, 0)如果select没有内部颜色,或Selection.Interior.Color = xlNone ifselect的内部颜色已经是红色的。 有效切换布尔属性。 例如,如果我想切换select的WrapText属性,我可以使用

 Sub ToggleWrapText() ' Toggles text wrap alignment for selected cells If TypeName(Selection) = "Range" Then Selection.WrapText = Not ActiveCell.WrapText End If End Sub 

以下过程不起作用,因为它只是简单地使selectxlNone并且当我再次单击控件窗体button时不会变回红色。

 Sub mcrToggleRed() ' Toggle the color for selected cells If TypeName(Selection) = "Range" Then Select Case Selection.Interior.Color Case xlNone Selection.Interior.Color = RGB(255, 0, 0) Case Selection.Interior.Color = RGB(255, 0, 0) Selection.Interior.Color = xlNone End Select End If End Sub 

我也试过了一个If...Then...Else循环,其结果与Select...Case循环的结果相同。 有任何想法吗?

您可以使用立即如果( IIf )这种事情:

 Sub mcrToggleRed() With Selection.Interior .Color = IIf(.Color = xlNone Xor .Color = 16777215, RGB(255, 0, 0), xlNone) End With End Sub 

注意:原始代码的实际问题是由于您正在testingxlNone作为默认值而导致的。 Gary的学生实际上发布了另一个testingRGB(255, 255, 255)答案 – 这是单元格的.Color属性的实际默认值。

虽然在我的代码中,我使用了16777215 (这是RGB(255, 255, 255) )的返回值) – 我最初忽略了你testing错误值的事实,如果是Gary的回答,还在。


(Gary发布的替代解决scheme(我已经添加了他的许可 ))

 Sub mcrToggleRed() ' Toggle the color for selected cells If TypeName(Selection) = "Range" Then Dim r As Range For Each r In Selection If r.Interior.Color = RGB(255, 255, 255) Then '//<~~ NOTE the RGB value r.Interior.Color = RGB(255, 0, 0) Else r.Interior.Color = RGB(255, 255, 255) End If Next r End If End Sub