Option Explicit
Declare Sub Sleep Lib "kernel32" _
(ByVal dwMilliseconds As Long)
Dim status As String
Sub StartModule()
Dim index As Integer
Dim result As String
Dim o: Set o = CreateObject("NAddIn.Functions")
status = ""
Do Until status = "DADA"
result = o.getRandomNumber
Range("F2").Value = result
Sleep123
If status = "EXIT" Then Exit Do
Loop
End Sub
Sub StopModule()
status = "EXIT"
End Sub
Sub Sleep123()
Sleep 1000 'Implements a 1 second delay
End Sub
此vba脚本调用名为getRandomNumber()
的调用,它是dll文件中的用户定义函数。通过单击开始按钮运行后,我能够运行连续生成随机数并在单元格中显示的功能。
问题是我无法点击停止按钮或编辑任何单元格,甚至我无法关闭xl文件。
答案 0 :(得分:1)
不要使用Sleep
API。 Sleep函数不仅在指定的时间间隔内暂停当前线程的执行,而且还不允许您执行任何其他操作。即它将冻结Excel。使用我多年前创建的自定义函数Wait
。
Option Explicit
Dim status As String
Sub StartModule()
Dim index As Integer
Dim result As String
Dim o: Set o = CreateObject("NAddIn.Functions")
status = ""
Do Until status = "DADA"
result = o.getRandomNumber
Range("F2").Value = result
Wait 1 '<~~ Wait for a second
If status = "EXIT" Then Exit Do
Loop
End Sub
Sub StopModule()
status = "EXIT"
End Sub
Private Sub Wait(ByVal nSec As Long)
nSec = nSec + Timer
While nSec > Timer
DoEvents
Wend
End Sub
顺便说一下,当你把一个计时器设置为1秒时,编辑单元格并不是一个好主意。当您处于编辑模式时,您将收到错误,因为Excel将无法写入单元格F2。在这种情况下,请考虑增加计时器:)