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
Finally, notice how, in the second to last line, we treat the function name GetUserName as if it were a variable. When using functions (as opposed to subprocedures, which do not return a value), this is how you give the function its return value. In a sense, the function name itself is a variable within the procedure.
Let's take a look at some code that uses the GetUserName function.
Dim Greeting
Din AnyName
AnyName = GetUserName
If Trim(AnyName( <> " " Then
Greeting = "Hello, " & AnyNAme & " Glad to meet you."
Else
Greeting = "I/m glad to meet you, but I wish I knew your name."
End If
MsgBox Greeting
If you are using the Windows Script Host to execute this code, keep in mind that the above code and the GetUserName function itself must be in the same .vbs file. As you can see, calling the GetUserNAme function is pretty straightforward. Once you have written a procedure, calling it is no different than calling a built-in VBScript procedure.
Breaking your code into modular procedures is very good habit to pick up.
First
Next