Loop An Input Box Until It Receives Correct or Valid Entry

Combine Input Box and Do Loop to read correct User Input

What This VBA Code Does

This VBA code will show how to keep cycling through an input box prompt until the user gives you a valid response.  My example below asks the user for his/her age and will continue to make the input box reappear in the event the user tries to be cute and enter an outrage age (such as "-20" or "200").  You will also need to make sure you capture if your user hits the Cancel button or else they may be looping forever!

Let me know in the comments section below how you plan to use this snippet to make sure your VBA code gets the proper inputs every time!

Sub LoopInputBox()
'PURPOSE: An example of how to keep looping an input box until a valid answer is entered
'SOURCE: www.TheSpreadsheetGuru.com/the-code-vault

Dim InputQuestion As String
Dim myAnswer As Variant

'Question to pose to the user
  InputQuestion = "Please enter your age." & vbNewLine _
    & "(Don't even think about lying!)"

'Keeping looping until you get a valid answer to your question
    'Retrieve an answer from the user
      myAnswer = Application.InputBox(InputQuestion, "Your Age?", Type:=1)
    'Check if user selected cancel button
      If TypeName(myAnswer) = "Boolean" Then Exit Sub
  Loop While myAnswer <= 0 Or myAnswer > 120

'We've got a valid answer from the user, let's continue on...

End Sub

How Do I Modify This To Fit My Specific Needs?

Chances are this post did not give you the exact answer you were looking for. We all have different situations and it's impossible to account for every particular need one might have. That's why I want to share with you: My Guide to Getting the Solution to your Problems FAST! In this article, I explain the best strategies I have come up with over the years to getting quick answers to complex problems in Excel, PowerPoint, VBA, you name it

I highly recommend that you check this guide out before asking me or anyone else in the comments section to solve your specific problem. I can guarantee 9 times out of 10, one of my strategies will get you the answer(s) you are needing faster than it will take me to get back to you with a possible solution. I try my best to help everyone out, but sometimes I don't have time to fit everyone's questions in (there never seem to be quite enough hours in the day!).

I wish you the best of luck and I hope this tutorial gets you heading in the right direction!

Chris "Macro" Newman :)