Continue procedure if CommandButton is clicked

与世无争的帅哥 提交于 2021-02-11 13:32:58

问题


So far I have used the below VBA in order to continue with a procedure if the user clicked ok in the MsgBox:

Sub Button_Message_Box()
Answer = MsgBox("Do you want to continue the procedure?", vbOK)
    If Answer = vbOK Then
    Sheet1.Range("A1").Value = 1
    Else
    End If
End Sub

Now I want to achieve the exact same result using CommandButton1 in UserForm1.
Therefore I tried to go with this:

(1) VBA in UserForm1:

Private Sub CommandButton1_Click()
Unload Me
End Sub

(2) VBA in Modul1:

Sub Button_Procedure()
Call UserForm1.Show(vbModeless)
If CommandButton1 = True Then
Sheet1.Range("A1").Value = 1
Else
End If
End Sub

The VBA goes through but it does not enter the value 1 into Cell A1.
What do I need to modify to achieve the desired result?


回答1:


I strongly suggest to follow the steps in this article: Rubberduck: UserForm1.Show

Nevertheless, a simple and dirty implementation could be as follows:

The form's code behind:

Add an event to raise when the OK-Cancel button has been pressed passing a boolean value indicating either to proceed or not:

Public Event OnClose(ByVal bool As Boolean)

Private Sub CmdOK_Click()
    RaiseEvent OnClose(True)
End Sub

Private Sub CmdCancel_Click()
    RaiseEvent OnClose(False)
End Sub

A simple wrapper class:

Here, we just instantiate the form and listen to the OnClose() event.

Option Explicit

Private WithEvents objForm As UserForm1
Private m_flag As Boolean

Public Function Show() As Boolean
    Set objForm = New UserForm1
    objForm.Show ' No vbModeless here, we want to halt code execution
    Show = m_flag
End Function

Private Sub CloseForm()
    Unload objForm
    Set objForm = Nothing
End Sub

Private Sub objForm_OnClose(ByVal bool As Boolean)
    m_flag = bool
    CloseForm
End Sub

Calling the wrapper class:

Sub Something()

    Dim bool As Boolean

    With New FormWrapper
        bool = .Show
    End With

    MsgBox "Should I proceed? " & bool
End Sub



回答2:


With reference to this question I used a Boolean variable:

(1) Code in UserForm1:

Private continue_procedure As Boolean

Private Sub CommandButton1_Click()
continue_procedure = True
Unload Me
End Sub

Function check_procedure() As Boolean
UserForm1.Show
check_procedure = continue_procedure
End Function

(2) Code in Modul1:

Sub Button_Procedure()
If UserForm1.check_procedure() = True Then
Sheet1.Range("A1").Value = 1
Else
End If
End Sub


来源:https://stackoverflow.com/questions/60639852/continue-procedure-if-commandbutton-is-clicked

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!