在Excel中,我希望根据当前单元格填充的颜色(类似于IFCOLOR() )在当前单元格中显示值。当我更改填充颜色时,Excel应自动完成此操作,因此应该是事件。
例如:当我用绿色填充单元格时,Excel在红色填充单元格时自动显示值100,然后Excel自动显示值75,等等。
是否可以在Excel中按事件执行此操作?或者你能给我其他的想法怎么做吗?
我使用了Workbook_SheetChange
,但是当我在单元格中更改值时,而不是在它的背景色中,这是可行的。
问候简
发布于 2017-03-13 10:17:37
你可以试试这样的东西:
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
发布于 2017-03-14 21:08:17
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
https://stackoverflow.com/questions/42760376
复制相似问题