Previous Section Table of Contents Next Section

Concatenating Strings

You've already learned about string concatenation, but let's look at it again. It's an important technique that you'll use repeatedly in your scripts.

For example, suppose you need to display a long, complicated message inside a message box. You could write a single MsgBox statement on a very long line of code, but that's harder to do and will make it tougher to maintain the script in the future. Instead, it's often easier to use string concatenation and line-continuation characters.


Dim sMessage

sMessage = "The server name you typed is invalid." & _

 vbCrLf & _

 vbCrLf & "Remember that all server names must : & _

 be seven characters " & _

 "long. The first three characters " & _

 must be the server's internal " & _

 "serial number. The second three characters " & _

 must be the three-" & _

 "character code for the office in which the " & _

 server is located. " & _

 "Finally, the last four characters indicate " & _

 the server's function:" & _

 vbCrLf & vbCrLf & "FILES = File Server" & _

 vbCrLf & vbCrLf & _

 "DOMC = Domain Controller" & vbCrLf & vbCrLf & _

 "SQLS = SQL Server" & vbCrLf & vbCrLf & _

 "Please try again."

MsgBox sMsg

I can't even show you the alternative in this book-there's no way for me to spread a single line of code across multiple pages!

String concatenation is also useful when you're working with variables. For example, suppose you need to generate some kind of unique password for new users. The following function might be used in a script that creates new user accounts.


Function MakePassword(sUserName)

 Dim sPassword

 sPassword = Left(sUserName,1)

 sPassword = sPassword & UCase(Right(sUserName,1))

 sPassword = sPassword & DatePart("n",Now)

 sPassword = sPassword & UCase(Mid(sUserName, 3, 2)

 MakePassword = sPassword

End Function

This function uses concatenation-and several other functions-to make up a reasonably complex password that can be assigned to new user accounts. String concatenation is used to append the results from each function to the gradually growing password, with a final password that's about seven characters long. I'll cover the DatePart() function in the next chapter, and I'll cover the UCase() function in the next section of this chapter.

NOTE

Remember that in Chapter 5 I explained how you could use both & and + for string concatenation. I mention it because you may see example scripts on the Web that use +; because + can also be used for addition, you should never use it for string concatenation. Always use &, which VBScript knows can only be used for concatenation.


    Previous Section Table of Contents Next Section