我知道此代码可用于创建带有两个命令按钮的闪烁单元:
Sub start_time()
Application.OnTime Now + TimeValue(“00:00:01”), “next_moment”
End Sub
Sub end_time()
Application.OnTime Now + TimeValue(“00:00:01”), “next_moment”, , False
End Sub
Sub next_moment()
If Worksheets(“Sheet1”).Cells(1, 1).Interior.ColorIndex = 6 Then
Worksheets(“Sheet1”).Cells(1, 1).Interior.ColorIndex = 0
Else
Worksheets(“Sheet1”).Cells(1, 1).Interior.ColorIndex = 6
End If
start_time
End Sub
VBA Code for First Command Button (“Start Blinking”)
Private Sub CommandButton1_Click()
Call start_time
End Sub
VBA Code for Second Command Button (“Stop Blinking”)
Private Sub CommandButton2_Click()
Call end_time
End Sub
我现在要做的是使TextBox闪烁,该闪烁会在10秒后自动停止。这也应该由命令按钮控制。但在这种情况下,只能闪烁一次,因为闪烁会自动停止。我的想法是使用TextBox的背景色,但我无法实现它。
答案 0 :(得分:1)
在工作表中
Sub CommandButton1_Click()
If PlayStopMacro = True Then
PlayStopMacro = False
Sheets("Sheet1").CommandButton1.BackColor = vbRed
Else
PlayStopMacro = True
Sheets("Sheet1").CommandButton1.BackColor = vbGreen
next_moment
Application.OnTime Now + TimeValue("00:00:05"), "StopMacro"
'Keep thi odd number to keep textbox backcolor white
End If
End Sub
在模块中
Public PlayStopMacro As Boolean
Sub next_moment()
If PlayStopMacro = True Then
If Sheets("Sheet1").TextBox1.BackColor <> RGB(255, 255, 255) Then
Sheets("Sheet1").TextBox1.BackColor = RGB(255, 255, 255)
Sheets("Sheet1").TextBox1.ForeColor = RGB(0, 0, 0)
Else
Sheets("Sheet1").TextBox1.BackColor = RGB(0, 0, 0)
Sheets("Sheet1").TextBox1.ForeColor = RGB(255, 255, 255)
End If
Application.OnTime Now + TimeValue("00:00:01"), "next_moment"
End If
End Sub
Sub StopMacro()
PlayStopMacro = False
Sheets("Sheet1").CommandButton1.BackColor = vbRed
End Sub
答案 1 :(得分:0)
尝试一下(将它们全部放在同一个模块中)
Option Explicit
Public dteStartTime As Date
Sub start_time()
Application.OnTime Now + TimeValue("00:00:01"), "next_moment"
End Sub
Sub end_time()
On Error Resume Next
Application.OnTime Now + TimeValue("00:00:01"), "next_moment", , False
On Error GoTo 0
End Sub
Sub next_moment()
If Worksheets("Sheet1").Cells(1, 1).Interior.ColorIndex = 6 Then
Worksheets("Sheet1").Cells(1, 1).Interior.ColorIndex = 0
Else
Worksheets("Sheet1").Cells(1, 1).Interior.ColorIndex = 6
End If
If dteStartTime + TimeValue("00:00:10") <= Now Then
end_time
Else
start_time
End If
End Sub
Sub CommandButton1_Click()
dteStartTime = Now
Call start_time
End Sub
答案 2 :(得分:0)
您可以声明一个Public
计数器变量(x
),该变量计数到10,然后停止调用start_time
。这意味着end_time
可以从代码中删除:
Public x
Sub Button1_Click()
Cells.Clear
Cells(1, 1) = 1
x = 1
start_time
End Sub
Sub start_time()
Application.OnTime Now + TimeValue("00:00:01"), "next_moment"
End Sub
Sub next_moment()
With Cells(1, 1).Interior
If .ColorIndex = 6 Then
.ColorIndex = 0
Else
.ColorIndex = 6
End If
End With
x = x + 1
Cells(1, 1) = x
If x < 10 Then start_time
End Sub
with
语句使代码更易于管理。 cells(1,1)
值会跟踪计数器,可以将其删除。