我有一个Outlook宏,当有人发送电子邮件并要求他们选择分类时,该宏会弹出一个表单。在ThisOutlookSession下,我有:
Private Sub Application_ItemSend(ByVal Item As Object, Cancel As Boolean)
Dim frm As classificationForm
Dim chosenvalue As String
Set frm = New classificationForm
frm.Show vbModal
Select Case True
Case frm.restrictedButton.Value
chosenvalue = "Restricted"
Case frm.internalButton.Value
chosenvalue = "Internal"
Case frm.publicButton.Value
chosenvalue = "Public"
Case Else
MsgBox "No classification chosen"
Cancel = True
Exit Sub
End Select
If TypeName(Item) = "MailItem" Then
Item.Subject = "[" & chosenvalue & "] " & Item.Subject
End If
End Sub
在分类表格下,我有:
Private Sub okCommand_Click()
Unload Me
End Sub
Private Sub cancelCommand_Click()
Unload Me
End Sub
该表单是3个选项按钮(分类)和2个命令按钮(确定和取消)。
默认选择[内部]选项按钮。但是,如果有人单击窗体右上角的“ X”按钮或“取消”命令按钮,则当我希望它将我踢回到电子邮件草稿时,宏会发送带有所选分类按钮的电子邮件。如果未选择任何选项,将是这样。
我该怎么做?谢谢。
答案 0 :(得分:1)
Unload
是个谎言。它似乎仅适用于表单的默认实例,而使用表单的默认实例是您不想去的有毒地方。
不要卸载。改为Hide
。
另一个问题是,由于调用代码正在查询表单控件的状态,因此关闭表单的方式无关紧要:确定,取消,“ X”-这些按钮中的任何一个都会卸载表单,无论如何被选中将被执行:您没有适当的机制来确定用户是否同意对话框,还是希望取消所有操作。
添加一个Cancelled
属性:
Private IsCancelled As Boolean
Public Property Get Cancelled() As Boolean
Cancelled = IsCancelled
End Property
处理QueryClose
事件,在Cancel
为False
时将CloseMode
参数设置为vbFormControlMenu
,并以Hide
的形式-实际上,您想要的是使该“ X”按钮执行与您的取消按钮完全相同的操作,因此只需执行以下操作:
Private Sub OkButton_Click()
Me.Hide
End Sub
Private Sub CancelButton_Click()
OnCancel
End Sub
Private Sub UserForm_QueryClose(Cancel As Integer, CloseMode As Integer)
If CloseMode = VbQueryClose.vbFormControlMenu Then
Cancel = True
OnCancel
End If
End Sub
Private Sub OnCancel()
IsCancelled = True
Me.Hide
End Sub
现在,您的呼叫代码可以确定表单是否已取消,并采取相应措施。
If frm.Cancelled Then
Cancel = True
Else
'user okayed the dialog: determine the selection...
End If
有关用户表单的更多详细信息,请参见this article:调用代码不需要 来关心表单上的控件。
答案 1 :(得分:0)
使用UserForm_QueryClose()
事件处理程序来拦截任何用户形式的红色“ X”点击
然后按如下所示更改您的UserForm
代码窗格:
Private Sub okCommand_Click()
Me.Hide ' don't unload the Form, just hide it
End Sub
Private Sub cancelCommand_Click()
Me.Tag = "NO" ' signal to the calling sub that it must not send the email
Me.Hide ' don't unload the Form, just hide it
End Sub
Private Sub UserForm_QueryClose(Cancel As Integer, CloseMode As Integer)
If CloseMode = 0 Then Me.Tag = "NO" ' if user clicked the red X button signal to the calling sub that it must not send the email
End Sub
并相应地调整您的Application_ItemSend
事件处理程序代码:
Set frm = New classificationForm
With frm
.Show vbModal
If .Tag <> "NO" Then ' if userform didn't signal not to send the email
Select Case True
Case frm.restrictedButton.Value
chosenvalue = "Restricted"
Case frm.internalButton.Value
chosenvalue = "Internal"
Case frm.publicButton.Value
chosenvalue = "Public"
Case Else
MsgBox "No classification chosen"
Cancel = True
Exit Sub
End Select
Else ' the userform signaled not to send the email
MsgBox "No classification chosen"
Cancel = True
End If
End With
Unload frm