如何根据填充的颜色在单元格中显示值 - Excel VBA中的事件

时间:2017-03-13 09:36:44

标签: excel vba events

在Excel中,我想在当前单元格中显示值,具体取决于其填充颜色(类似于IFCOLOR())。 Excel应该在我更改填充颜色时自动执行此操作,因此它应该是事件。

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

是否可以通过Excel VBA中的事件执行此操作?或者你能告诉我其他想法吗?

我使用了22.00%,但是当我更改单元格中的值而不是其背景颜色时,这是有效的。

此致 扬

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

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