如何使过程在按下按钮的同时运行?

时间:2019-02-15 20:19:19

标签: vba ms-access access-vba

我使用:
-赢7x64;
-访问-2016年;

我尝试使用以下代码解决问题。
Form1

Option Compare Database
Option Explicit

Public statusBool As Boolean
Public numProc As Integer

' `Button pressed`.
Private Sub btnStart_Click()
        numProc = 0
        statusBool = True

        Call Process(statusBool, numProc)

End Sub

' Process
Public Sub Process(statusBool As Boolean, numProc As Integer)
        If statusBool = True Then

           Me.txtProcessFrm = "ProcessNum - " & numProc + 1
            Call SleepFor(1000)  '1 seconds delay

           Call Process(statusBool, numProc)
        End If

End Sub

'
Private Sub btnStart_MouseUp(Button As Integer, Shift As Integer, X As Single, Y As Single)
    statusBool = False
    numProc = 0
    Call Process(statusBool, numProc)
End Sub


Public Sub SleepFor(ByVal MilliSeconds As Long)
    Sleep MilliSeconds
End Sub

Module1

Option Compare Database
Option Explicit

Private Declare PtrSafe Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As Long)

问题
我的解决方案是否适合此任务,或者有更简单的方法来解决此问题?

enter image description here

更新_1
该代码无法启动。
我收到错误Sub or Function not definedenter image description here

更新_2
模块Module1
Private替换为Public

Private Declare PtrSafe Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As Long)

它变成了
Public Declare PtrSafe Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As Long)

问题。
当我单击按钮btnStart_Click时文件挂起

Update_3
修改过的过程(statusBool为布尔值,numProc为整数)
变成了。

 ' Process
    Public Sub Process(statusBool As Boolean, numProc As Integer)
            If statusBool = True Then
                Do
                        Sleep 1000
                        DoEvents
                Loop Until Me.txtProcessFrm = "ProcessNum - " & numProc + 1

               Call Process(statusBool, numProc)
            End If

    End Sub

问题。
暂停似乎有效,但是逻辑本身不起作用。
换句话说,文本字段中没有文本。
如果释放按钮,循环将继续进行。

1 个答案:

答案 0 :(得分:1)

单击按钮的事件链如下。

MouseDown → MouseUp → Click → DblClick → Click

在您的代码中,循环永远不会停止,因为statusBool始终为true会导致无限循环,这也许就是即使您释放mosue也会挂起的原因。

不过,您可以按下鼠标=>鼠标向上

Private Sub btnStart_MouseDown(Button As Integer, Shift As Integer, X As Single, Y As Single)
    statusBool = True
    Call Process(0)
End Sub

Private Sub btnStart_MouseUp(Button As Integer, Shift As Integer, X As Single, Y As Single)
    statusBool = False
End Sub

Public Sub Process(numProc As Integer)
    If statusBool Then
        numProc = numProc + 1
        Me.txtProcessFrm = "ProcessNum - " & numProc
        Sleep 1000
        DoEvents

        Call Process(numProc)
    End If
End Sub

更多信息: https://docs.microsoft.com/en-us/office/vba/api/access.commandbutton.click