2014-10-08 158 views
15

我有一个输入框要求用户输入日期。如果用户单击取消或关闭输入对话框而不是按下OK,我该如何让程序知道停止。如何检测用户是否选择取消InputBox VBA Excel

喜欢的东西 if str=vbCancel then exit sub

目前,用户可以点击确定或取消,但该计划仍然运行

str = InputBox(Prompt:="Enter Date MM/DD/YYY", _ Title:="Date Confirmation", Default:=Date) enter image description here

回答

21

如果用户点击取消,零长度字符串返回。您无法区分这与输入空字符串。但是你可以让你自己定制的InputBox类...

你的榜样

Private Sub test() 
    Dim Str As String 
    Str = InputBox("Enter Date MM/DD/YYY", "Date Confirmation", Now) 
    If Str = vbNullString Then 
     MsgBox ("User canceled!") 
    End If 
End Sub 

会告诉他们时,删除默认字符串,或者单击取消他们取消了用户。

http://msdn.microsoft.com/en-us/library/6z0ak68w(v=vs.90).aspx

+0

感谢 - 它应该已经Vbnullstring代替vbCancel – user2103670 2014-10-08 19:33:13

+0

@ user2103670是不幸的是'InputBox'返回代替按钮点击为'MsgBox'确实值。 – djv 2014-10-08 19:34:40

+0

@DanVerdolino如果您使用声明的字符串变量进行测试,那么这是真的。但正如Siddharth指出的那样,您也可以使用按钮。 – guitarthrower 2014-10-08 19:38:29