如何在单元格中显示值取决于其填充颜色 – Excel VBA中的事件

在Excel中,我希望根据其填充颜色(如IFCOLOR())显示当前单元格中的值。 当我改变填充颜色时,Excel应该自动执行此操作,因此它应该是事件。

例如:当我用绿色填充单元格时,Excel会自动显示值100当我用红色填充单元格然后自动Excel显示值75等等…

Excel VBA中的事件可以做到这一点吗? 或者你可以给我其他的想法如何做到这一点?

我使用了Workbook_SheetChange但是当我更改单元格中的值而不是其背景颜色时,它可以正常工作。

问候1月

你可以尝试这样的事情:

 Private Sub Worksheet_SelectionChange(ByVal Target As Range) If ActiveCell.Interior.Color = vbRed Then ActiveCell = 75 Else ActiveCell = " " End If End Sub 

预定范围:

 Private Sub Worksheet_SelectionChange(ByVal Target As Range) Application.Calculation = xlCalculationManual Application.ScreenUpdating = False Dim ws As Worksheet Set ws = ThisWorkbook.Worksheets("Sheet1") Dim rng As Range, cell As Range Set rng = ws.Range(Cells(1, 1), Cells(100, 20)) For Each cell In rng If cell.Interior.Color = RGB(255, 0, 0) Then cell = 75 ElseIf cell.Interior.Color = RGB(0, 255, 0) Then cell = 100 Else cell = " " End If Next cell Application.Calculation = xlCalculationAutomatic Application.ScreenUpdating = True End Sub 

CommandBars.OnUpdate可以用来处理大多数自定义事件。 在ThisWorkbook对象中:

 Private WithEvents bars As CommandBars, color As Double Private Sub bars_OnUpdate() 'If Not ActiveSheet Is Sheet1 Then Exit Sub ' optional to ignore other sheets If ActiveCell.Interior.color = color Then Exit Sub ' optional to ignore if same color color = Selection.Interior.color 'Debug.Print Selection.Address(0, 0), Hex(color) If color = vbGreen Then Selection = 100 Else _ If color = vbRed Then Selection = 75 End Sub Private Sub Workbook_Activate() Set bars = Application.CommandBars ' to set the bars_OnUpdate event hook End Sub Private Sub Workbook_Deactivate() Set bars = Nothing ' optional to unset the bars_OnUpdate event hook End Sub Private Sub Workbook_SheetSelectionChange(ByVal Sh As Object, ByVal Target As Range) color = Selection.Interior.color ' optional to ignore selection change events End Sub 

上面的示例不处理所有的边缘情况,但可以根据需要进行调整。


对于其他自定义事件,应尽可能使用更具体的CommandBarControl事件:

 CommandBarButton.Click CommandBarComboBox.Change CommandBarControl.OnAction CommandBarPopup.OnAction