Excel - 双击更改行的字体颜色

Excel - 双击更改行的字体颜色

我尝试在双击单元格所在行时将其字体颜色从黑色更改为灰色,在单元格已经是灰色时将其字体颜色改为相反的颜色。以下是我正在尝试的代码:

 Private Sub Worksheet_BeforeDoubleClick(ByVal Target As Excel.Range, Cancel As Boolean)
   If Target.FormatConditions.Item.Font.ColorIndex <> 0 Then
     Cell.EntireRow.FormatConditions.Item.Font.ColorIndex = 0
   Else
     Target.FormatConditions.Item.Font.ColorIndex = 8
   End If
   Cancel = True
End Sub

答案1

我不明白你为什么要设置条件格式。你可以直接对字体颜色进行操作。黑色 = 颜色索引 1,灰色 = 颜色索引 16:

 Private Sub Worksheet_BeforeDoubleClick(ByVal Target As Excel.Range, Cancel As Boolean)
     If Target.Font.ColorIndex <> 1 Then
         'not black? -> set to black
         Target.EntireRow.Font.ColorIndex = 1
     Else
         'black? -> set to grey
         Target.EntireRow.Font.ColorIndex = 16
     End If
     Cancel = True
End Sub

此代码仅适用于您在 VBA 编辑器中输入代码的特定工作表。

要使操作自动应用于工作簿中的每个工作表,您需要将过程声明中的事件引用更改为Workbook_SheetBeforeDoubleClick(ByVal Sh As Object, ByVal Target As Range, Cancel As Boolean)

必须将修改后的代码输入到编辑器的代码窗格中ThisWorkbook。(无需修改代码主体。)

如果要将操作及其结果限制到特定的列或行,则只需要适度改变方法:

Private Sub Workbook_SheetBeforeDoubleClick(ByVal Sh As Object, ByVal Target As Range, Cancel As Boolean)
'   only double-clicks in columns B and C will trigger action
    If Not Intersect(Target, Sh.Range("B:C")) Is Nothing Then
        If Target.Font.ColorIndex <> 1 Then
'           only fonts in columns B and C will be modified
            Sh.Range("B:C").Font.ColorIndex = 1
        Else
            Sh.Range("B:C").Font.ColorIndex = 16
        End If
        Cancel = True
    End If
End Sub

相关内容