How to Check if a User Clicked [Cancel] on an InputBox in VBA
It's possible to distinguish between a user clicking [OK] on an empty box or clicking [Cancel]. You just need to use this simple trick.
![How to Check if a User Clicked [Cancel] on an InputBox in VBA](/content/images/size/w2000/2021/08/ladybugs-1593406_1920.jpg)
Did you know that it's possible to distinguish between a user clicking "OK" on an InputBox versus "Cancel", even if they did not enter any text?
Consider the following sample code:
Sub InputBoxTest()
Dim Result As String
Result = InputBox("Leave this box blank")
If StrPtr(Result) = 0 Then
Debug.Print "User clicked [Cancel]"
ElseIf Len(Result) = 0 Then
Debug.Print "User clicked [OK]"
Else
Debug.Print "User can't follow instructions"
End If
End Sub
Here is the test code in action:
![](https://nolongerset.com/content/images/2021/08/InputBox.gif)
If you're interested in why this works, I recommend the following question on stackoverflow: What are the benefits and risks of using StrPtr in VBA? Both top-voted answers (from users Comintern and GSerg) are worth reading for background knowledge.
External references
![](https://cdn.sstatic.net/Sites/stackoverflow/Img/apple-touch-icon@2.png?v=73d79a89bded)
Image by Ron van den Berg from Pixabay