【问题标题】:How to handle the InputBox cancel button?如何处理 InputBox 取消按钮?
【发布时间】:2019-05-20 08:40:31
【问题描述】:

我输入开始日期和结束日期并执行从 Outlook 导出的代码。

Sub ExportFromOutlook()
Dim dteStart As Date
Dim dteEnd As Date

dteStart = InputBox("What is the start date?", "Export Outlook Calendar")
dteEnd = InputBox("What is the end date?", "Export Outlook Calendar")
Call GetCalData(dteStart, dteEnd)
End Sub

我希望当我按下任何输入框上的 “取消按钮” 时退出 sub,而不是在 VBA 代码中出现错误来调试它。

【问题讨论】:

  • 您将不得不捕获错误。 VBA 中的每个错误都会返回一个特定的数字。您可以处理错误,当用户按下Cancel,然后退出子。

标签: excel vba


【解决方案1】:

不合格的InputBoxVBA.InputBox。它返回一个String,而不是日期,然后你use StrPtr 来确定是否按下了取消:

Dim dteStart As Date
Dim dteEnd As Date
Dim t as string

t = InputBox("What is the start date?", "Export Outlook Calendar")
If StrPtr(t) = 0
  Exit Sub
Else
  dteStart = CDate(t)
End If

t = InputBox("What is the end date?", "Export Outlook Calendar")
If StrPtr(t) = 0
  Exit Sub
Else
  dteEnd = CDate(t)
End If

如果你切换到 Excel 的 Application.InputBox,它返回 Variant,它可能会变得更简单一点:

Dim dteStart As Date
Dim dteEnd As Date
Dim t as Variant

t = Application.InputBox("What is the start date?", "Export Outlook Calendar", Type:=2)
If t = False
  Exit Sub
Else
  dteStart = CDate(t)
End If

t = Application.InputBox("What is the end date?", "Export Outlook Calendar", Type:=2)
If t = False
  Exit Sub
Else
  dteEnd = CDate(t)
End If

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-11-05
  • 2012-07-14
  • 1970-01-01
  • 1970-01-01
  • 2017-08-12
  • 2012-12-17
相关资源
最近更新 更多