Code Inside The Function

Function GetUserName
'Prompts the user for his name. If the user refuses to provide
''his name five times, we give up and return a zero-length string.
Dim UserName
Dim TryAgain
Dim LoopCount
LoopCount = 1
Do
TryAgain = "No"
UserName = InputBox("Please enter your name:")
UserName = Trim(UserNAme)
If UserName = " " Then
If LoopCount > 5 Then
UserName = " "
TryAgain = "No"
Else
MsgBox "You must enter your name."
TryAgain = "Yes"
End If
LoopCount = LoopCount + 1
Loop While TryAgain = "Yes"
GetUserNAme = UserNAme
End Function

The code inside the function is very similar to the code I used in the discussion of loops. I have introduced one new element, though: the LoopCount variable. I am using this variable to count the number of times we go through the loop. Before we start the loop, we initialize LoopCount with the numeric value of zero. Then, at the beginning of each loop, we increment the value of LoopCount by 1. If we go through the loop more than five times without the user entering his name, we stop asking and set the user name to a blank string (represented by " ").

First
Next