InputBox取消按钮退出子问题

时间:2019-05-20 08:40:32

标签: excel vba

关于输入框和其中的一部分“取消”按钮,我有一个或多或少愚蠢的问题无法解决。

这是代码:

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

这个想法是,在我输入开始日期和结束日期之后,我正在执行从Outlook导出的代码,但这不是重点。

我想要实现的是,当我按下任意输入框上的“取消按钮” 退出子菜单时,不会在VBA代码中出错来对其进行调试。

谢谢!

1 个答案:

答案 0 :(得分:4)

不合格的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

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

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