我想创建一个具有无限循环的宏。在这个循环中,我每秒更改一次单元格的值。
我想手动更改单元格而不停止宏(代码中的Alpha变量)。是否有任何解决方法可以实现?还是线程?
这是我的代码:
Sub test()
Dim wb As Workbook
Dim ws As Worksheet
Dim i As Integer
i = 0
Set wb = ActiveWorkbook
Set ws = wb.Sheets("Sheet1")
Set P1 = ws.Range("A1")
Set Q1 = ws.Range("A2")
Set Alpha = ws.Range("G1")
On Error GoTo CleanExit
If Target.Address = "$Q$21" Then
Application.EnableEvents = False
End If
CleanExit:
Application.EnableEvents = True
While i = 0
P1.Value = 100 + WorksheetFunction.RandBetween(1, 6)
Q1.Value = Alpha
Pause (1)
Wend
On Error GoTo 0
End Sub
这是暂停功能:
Public Function Pause(NumberOfSeconds As Variant)
On Error GoTo Error_GoTo
Dim PauseTime As Variant
Dim Start As Variant
Dim Elapsed As Variant
PauseTime = NumberOfSeconds
Start = Timer
Elapsed = 0
Do While Timer < Start + PauseTime
Elapsed = Elapsed + 1
If Timer = 0 Then
' Crossing midnight
PauseTime = PauseTime - Elapsed
Start = 0
Elapsed = 0
End If
DoEvents
Loop
Exit_GoTo:
On Error GoTo 0
Exit Function
Error_GoTo:
Debug.Print Err.Number, Err.Description, Erl
GoTo Exit_GoTo
End Function
当我选择单元格时,我得到错误1004“应用程序定义或对象定义的错误”
基本上,我想模拟液压泵的功能,有一个角度α变化。如果alpha改变了其他参数(压力,流量......)的变化。这就是为什么我想在参数上连续循环,每秒都有一些错误(使用随机函数)。当alpha改变(手动)时,参数改变值。这是主要的想法。
答案 0 :(得分:3)
对于使用工作表中的数据重复计算,我将使用如下结构。它使用Application.OnTime
事件重复运行该过程(〜每秒),直到满足某些条件(或调用停止过程)。我使用了一些简单的代码来表明您可以在工作表中输入数据:
Option Explicit
Private Running As Boolean
Sub Start_Timer()
Running = True
Application.OnTime Now + TimeSerial(0, 0, 1), "Timed_Code"
End Sub
Sub Stop_Timer()
Running = False
End Sub
Sub Timed_Code()
If [A1] = False Then Call Stop_Timer
[C1] = [B1] + Application.WorksheetFunction.RandBetween(1, 6)
If Running Then Application.OnTime Now + TimeSerial(0, 0, 1), "Timed_Code"
End Sub