簡體   English   中英

如何使用VBA切換Interior.Color

[英]How to Toggle Interior.Color using VBA

我想有一個窗體控制按鈕,該控件使用VBA將選擇更改為Selection.Interior.Color = RGB(255, 0, 0)如果選擇沒有內部顏色),或者將Selection.Interior.Color = xlNone更改為選擇的內部顏色已經是紅色。 有效地切換布爾屬性。 例如,如果要切換選擇的WrapText屬性,則可以使用

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

下面的過程不起作用,因為它僅使選擇xlNone成為可能,並且當我再次單擊控件表單按鈕時,它不會變回紅色。

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循環相同。 有任何想法嗎?

您可以對此類事情使用“即時If( IIf )”:

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

注意:原始代碼的實際問題是由您測試xlNone作為默認值引起的。 Gary的學生實際上發布了另一個答案,該答案測試了RGB(255, 255, 255) -這是單元格.Color屬性的實際默認值。

盡管在我的代碼中我使用的是16777215 (這是RGB(255, 255, 255) )的返回值)-我最初忽略了您正在測試錯誤值的事實,但Gary的答案會更清楚一些。還在。


(Gary發布的替代解決方案(我已在他的允許下添加))

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM