Excel 如果单击CommandButton,则继续此过程
到目前为止,如果用户在Excel 如果单击CommandButton,则继续此过程,excel,vba,Excel,Vba,到目前为止,如果用户在MsgBox中单击ok,我已经使用了下面的VBA,以便继续执行一个过程: 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 现在我想使用UserForm1中的Command
MsgBox
中单击ok
,我已经使用了下面的VBA
,以便继续执行一个过程:
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
现在我想使用
UserForm1
中的CommandButton1
获得完全相同的结果因此,我尝试这样做: (1)用户表单1中的VBA:
Private Sub CommandButton1_Click()
Unload Me
End Sub
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)模块1中的VBA:
Sub Button_Procedure()
Call UserForm1.Show(vbModeless)
If CommandButton1 = True Then
Sheet1.Range("A1").Value = 1
Else
End If
End Sub
Sub Button_Procedure()
If UserForm1.check_procedure() = True Then
Sheet1.Range("A1").Value = 1
Else
End If
End Sub
VBA
会通过,但不会将值1
输入单元格A1
我需要修改什么才能达到预期的结果?我强烈建议遵循本文中的步骤: 然而,一个简单而肮脏的实现可以如下所示: 表单的代码隐藏: 当按下OK Cancel(确定取消)按钮并传递一个指示继续或不继续的布尔值时,添加要引发的事件:
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
一个简单的包装类:
Sub Something()
Dim bool As Boolean
With New FormWrapper
bool = .Show
End With
MsgBox "Should I proceed? " & bool
End Sub
在这里,我们只是实例化表单并侦听OnClose()
事件
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
调用包装类:
Sub Something()
Dim bool As Boolean
With New FormWrapper
bool = .Show
End With
MsgBox "Should I proceed? " & bool
End Sub
关于问题,我使用了一个布尔变量:
(1)用户表单中的代码1:
Private Sub CommandButton1_Click()
Unload Me
End Sub
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)模块1中的代码:
Sub Button_Procedure()
Call UserForm1.Show(vbModeless)
If CommandButton1 = True Then
Sheet1.Range("A1").Value = 1
Else
End If
End Sub
Sub Button_Procedure()
If UserForm1.check_procedure() = True Then
Sheet1.Range("A1").Value = 1
Else
End If
End Sub
为什么不将代码附加到单击事件?不确定您试图通过以下方式实现什么:
如果CommandButton1=True,那么
?您正在以无模式
模式打开表单;在按下表单上的任何按钮之前,if条件将满足很长一段时间(这就是我假设CommandButton1的值的来源?)。在这种情况下,CommandButton1在该阶段永远不会为真