Trim Function in Do...Loop Code

Dim Greeting
Dim UserName
Dim TryAgain
Do
TryAgain = "No"
UserName = "InputBox("Please enter your name:")
If Trim(UserName) = " " Then
MsgBox "You must enter your name."
TryAgain = "Yes"
Else
Greeting = "Hello. " & UserName & ", it's a pleasure to meet you."
End If
Loop While TryAgain = "Yes"
MsgBox Greeting

Do
TryAgain = "No"
UserName = "InputBox("Please enter your name:")
If Trim(UserName) = " " Then
MsgBox "You must enter your name."
TryAgain = "Yes"
Else
Greeting = "Hello. " & UserName & ", it's a pleasure to meet you."
End If

Now we are testing our input. The line IF Trim(UserName) = " " Then tests to see if the user typed in their name. If they typed something in, the code immediately after the Else line will execute. If they did not (or if they clicked the Cancel button), then the UserName variable will be empty, and the code after the If line will execute instead. If the user did not type in their name, we display a message informating them that they have done something our script did not like. Then we set the TryAgain variable (our "control" variable) to "Yes". This ensures that the loop will go around again, and then we'll ask the user for their name again.

If the user did type their name, then we initialize our familiar Greeting variable. Note that in this case, we do not change the value of the TryAgain variable. This is because there is no need to loop around again - the user has obliged us and entered their name. The value of TryAgain is already equal to "No", so there's no need to change it.

First
Next