0

I type in the start date and the end date and execute a code of export from 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 

I want when I press the "Cancel button" on any of the Inputboxes to exit the sub, not to get an error in the VBA code to debug it.

1
  • 1
    You will have to trap the error. Each error in VBA will return a specific number. You can handle the error and the, when the user press Cancel, then Exit sub. Commented May 20, 2019 at 8:44

1 Answer 1

6

Unqualified InputBox is VBA.InputBox. It returns a String, not a date, and you use StrPtr to determine if Cancel was pressed:

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 

If you switch to Excel's Application.InputBox, which returns Variant, it may become a little bit more straightforward:

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 
Sign up to request clarification or add additional context in comments.

12 Comments

Maybe there should be also an error handler for the case that the user entered something invalid.
@FunThomas There should be, but there wasn't one originally either.
Just wanted to prevent the follow up quesion ;-)
@Flaw98 IsDate will always be false when StrPtr is zero.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.