The VBA String Function
The VBA String function creates a String, consisting of a number of repeated characters.
The syntax of the function is:
String( Number, Character )
Where the function arguments are:
The number of characters in the returned String.
A character code or a String, representing the character that is to be repeated in the returned String.
If the Character argument is a character code, this should be an Integer between 0 and 255. If a number that is greater than 255 is supplied, the String function converts this to a valid character code, using the formula:
Character = Character Mod 256
- If Character is a String containing more than one character, only the first character of the String is used in the returned String.
If the Number or Character arguments are Null, the String function returns Null.
VBA String Function Examples
The following VBA code uses the String function to create the String "aaaaaaaaaa" using three different Character arguments.
Dim str1 As String
Dim str2 As String
Dim str3 As String
str1 = String( 10, 97 )
str2 = String( 10, "a" )
str3 = String( 10, "alpha" )
In the above example, the three calls to the String function all return the String "aaaaaaaaaa".
In the first call to the String function, the supplied Character argument is the character code 97, which is the character code for the character "a".Therefore the String function returns the character "a" repeated 10 times.
In the third call to the String function, the supplied Character argument is the String "alpha".The String function only uses the first character of a supplied String and so, in this case also, the function returns the character "a" repeated 10 times.
VBA String Function Error
If you supply a negative Number argument to the VBA String function, you will get the error:
Run-time error '5': Invalid procedure call or argument