如何检测用户是否选择取消InputBox VBA Excel

您所在的位置:网站首页 vba停止刷新 如何检测用户是否选择取消InputBox VBA Excel

如何检测用户是否选择取消InputBox VBA Excel

2023-03-27 07:58| 来源: 网络整理| 查看: 265

我有一个输入框,要求用户输入日期。如果用户单击"取消"或关闭输入对话框而不是按"确定",我如何让程序知道停止。

类似的东西 if str=vbCancel then exit sub

当前,用户可以单击"确定"或"取消",但是程序仍在运行

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

如果用户单击"取消",则返回零长度的字符串。您无法将其与输入空字符串区分开。但是,您可以创建自己的自定义InputBox类...

根据此答案进行编辑以正确区分空字符串和取消。

您的示例

1234567891011Private Sub test()     Dim result As String     result = InputBox("Enter Date MM/DD/YYY","Date Confirmation", Now)     If StrPtr(result) = 0 Then         MsgBox ("User canceled!")     ElseIf result = vbNullString Then         MsgBox ("User didn't enter anything!")     Else         MsgBox ("User entered" & result)     End If End Sub

将告诉用户在删除默认字符串时已取消,或者单击"取消"。

请参阅http://msdn.microsoft.com/zh-cn/library/6z0ak68w(v = vs.90).aspx

相关讨论 谢谢-应该是Vbnullstring而不是vbCancel @DanVerdolino如果对测试使用声明的String变量,则为true。但是正如Siddharth所指出的,您也可以使用所按下的按钮。

以下示例使用InputBox方法来验证用户输入以取消隐藏工作表: 重要的是在StrPtr中使用wrap InputBox变量,以便当用户选择在InputBox上单击" x"图标时,可以将其与" 0"进行比较。

1234567891011121314151617Sub unhidesheet() Dim ws As Worksheet Dim pw As String pw = InputBox("Enter Password to Unhide Sheets:","Unhide Data Sheets") If StrPtr(pw) = 0 Then    Exit Sub ElseIf pw = NullString Then    Exit Sub ElseIf pw = 123456 Then     For Each ws In ThisWorkbook.Worksheets         ws.Visible = xlSheetVisible     Next End If End Sub

上述解决方案并非在所有InputBox-Cancel情况下都适用。最值得注意的是,如果必须输入框一个范围,它将不起作用。

例如,尝试使用以下InputBox定义自定义范围(" sRange",类型:= 8,需要设置Application.InputBox),然后按"取消"会出现错误:

123456789Sub Cancel_Handler_WRONG() Set sRange = Application.InputBox("Input custom range", _    "Cancel-press test", Selection.Address, Type:=8) If StrPtr(sRange) = 0 Then  'I also tried with sRange.address and vbNullString     MsgBox ("Cancel pressed!")     Exit Sub End If     MsgBox ("Your custom range is" & sRange.Address) End Sub

在这种情况下,唯一起作用的是末尾InputBox ErrorHandler之前的" On Error GoTo ErrorHandler"语句:

123456789Sub Cancel_Handler_OK() On Error GoTo ErrorHandler Set sRange = Application.InputBox("Input custom range", _    "Cancel-press test", Selection.Address, Type:=8) MsgBox ("Your custom range is" & sRange.Address) Exit Sub ErrorHandler:     MsgBox ("Cancel pressed") End Sub

所以,问题是如何使用If语句检测错误或StrPtr()= 0?

相关讨论 如果使用Application.InputBox,则StrPtr()=0检查将不起作用。为了使其正常工作,您只需要使用InputBox。



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3