当单元格是某个值时调用sub

时间:2013-08-12 21:11:55

标签: vba excel-vba excel

如果单元格N63的值为0,我想调用我的sub导致单元格在红色和白色之间闪烁。换句话说,如果单元格D70 = 0然后StartBlinking,则StopBlinking。

这是Bliking子

Option Explicit

Public NextBlink As Double
'The cell that you want to blink
Public Const BlinkCell As String = "Sheet1!D70"

'Start blinking
Public Sub StartBlinking()
    Application.Goto Range("A1"), 1
    'If the color is red, change the color and text to white
    If Range(BlinkCell).Interior.ColorIndex = 3 Then
        Range(BlinkCell).Interior.ColorIndex = 0
        Range(BlinkCell).Value = "White"
    'If the color is white, change the color and text to red
    Else
        Range(BlinkCell).Interior.ColorIndex = 3
        Range(BlinkCell).Value = "Red"
    End If
    'Wait one second before changing the color again
    NextBlink = Now + TimeSerial(0, 0, 1)
    Application.OnTime NextBlink, "StartBlinking", , True
End Sub

'Stop blkinking
Public Sub StopBlinking()
    'Set color to white
    Range(BlinkCell).Interior.ColorIndex = 0
    'Clear the value in the cell
    'Range(BlinkCell).ClearContents
    On Error Resume Next
    Application.OnTime NextBlink, "StartBlinking", , False
    Err.Clear
End Sub

这是我的if不起作用:

    If Worksheets("Sheet1").Range("N63").Value = 0 Then
        Call StartBlink()
    Else
        Call StopBlink()
    End If

如何调用这两个潜艇?

1 个答案:

答案 0 :(得分:2)

利用Worksheet_Change event,您可以针对特定范围的每次更改运行一些代码。以下是根据您的用例量身定制的示例:

Private Sub Worksheet_Change(ByVal Target As Range)
    Dim KeyCells As Range

    ' The variable KeyCells contains the cells that will
    ' cause an alert when they are changed.
    Set KeyCells = Range("D70")

    If Not Application.Intersect(KeyCells, Range(Target.Address)) Is Nothing Then
        If KeyCells.Value = 0 Then 
            StartBlinking
        Else 
            StopBlinking
        End If
    End If
End Sub