Wincc Text List Assignment Index

This topic contains information about handling strings in VBScript and provides examples of operations that deal with strings. It contains the following sections:


A String is a sequence of symbols or digits. Strings are among the most frequently used data types. Like any other data type, strings in TestComplete are represented as OLE-compatible variants. In VBScript, a sequence of literal characters, enclosed in double quotes ("), is recognized as a string. Single quotation marks (') are allowed within a string. To insert a double quotation mark into a string, it should be duplicated. The following is an example of string:

To deal with strings, TestComplete has a special scripting object. The object is available for all supported scripting languages, so that you can use it to operate with string values regardless of the chosen language.

Another scripting object that is useful for string manipulation is . This object has several methods that convert values of different types to a string representation and vice versa.

Furthermore, you can use native VBScript functions that operate with strings. A detailed description of VBScript functions can be found in the Functions (VBScript) article of the MSDN library. The table below only lists major functions:

Asc(string)Returns the ASCII character code corresponding to the first letter in a string.
Chr(charcode)Returns the character associated with the specified ANSI character code.
CStr(expression)Returns an expression that has been converted to a variant of sub-type string.
Escape(charString)Encodes a string so it only contains ASCII characters. Non-ASCII characters are replaced with %xx encoding, where xx is equivalent to the hexadecimal number representing the character.
InStr([startpos, ]string1, string2[, compare])Returns the position of the first occurrence for one string within another.The search can start at a given position and use binary (compare=0) or text (compare=1) comparisons.
InStrRev(string1, string2[, start[, compare]])Returns the position of an occurrence for one string within another, from the end of string. The search can start at a given position and use binary (compare=0) or text (compare=1) comparisons.
Join(list[, delimiter])Returns a string created by joining a number of substrings contained in an array.
LCase(string)Returns a string that has been converted to lowercase.
Left(string, length)Returns a specified number of characters from the left side of a string.
Len(string | varname)Returns the number of characters in a string or the number of bytes required to store a variable.
LTrim(string)Returns a copy of a string without leading spaces.
Mid(string, start[, length])Returns a specified number of characters from a string.
Replace(string, findstr, replacewith[, start[, count[, compare]]])Returns a string in which a specified substring has been replaced with another substring a specified number of times.
Right(string, length)Returns a specified number of characters from the right side of a string.
RTrim(string)Returns a copy of a string without trailing spaces.
Space(number)Returns a string consisting of the specified number of spaces.
Split(expression[, delimiter[, count[, compare]]])Returns a zero-based, one-dimensional array containing a specified number of substrings.
StrComp(string1, string2[, compare])Returns a value indicating the result of a string comparison.
String(number, character)Returns a repeating character string of the length specified.
StrReverse(string)Returns a string in which the character order of a specified string is reversed.
Trim(string)Returns a copy of a string without leading and trailing spaces.
UCase(string)Returns a string that has been converted to uppercase.
Unescape(charString)Decodes a string encoded with the Escape function.


str1 = "The brig was heading to Liverpool, when the captain noticed a ship."
str2 = "'Ahoy! Is there anyone?' - the captain cried."
str3 = """Nobody."" - was the answer."

Special characters

In VBScript you can emulate any character by using the function with the appropriate ASCII code. This also applies to special characters that are used to format string values. Alternatively, you can emulate control characters using native string constants. The table below lists the most frequently used special characters and their constants.

Carriage return.(13) -- or --
Line feed.
On Unix platforms it is interpreted as new line.
(10) -- or --
A combination of carriage return and line feed.
On Windows platforms it is interpreted as new line.
(13)+(10) -- or --
New line.
Either a line feed character or a combination of carriage return and line feed.
Form feed.(12) -- or --
Horizontal tab.(9) -- or --
Vertical tab.(11) -- or --

Special characters obtained by a function or constant should be joined to the string by concatenation:


Str1 = "A string." & Chr(13) & Chr(10) & "Another string."
Str2 = "A string." & vbNewLine & "Another string."

Getting the string length

To obtain the total number of characters in a string, you can call either the method, or the function of VBScript. The character position in VBScript is not zero-based, so the maximum position number in a string equals the string length. The following code demonstrates both ways of obtaining the string length:

Using TestComplete, you can limit the length of string parameters returned by functions of the tested application. For this purpose, use the Maximum string length of [out] parameters project property. If the length of the string returned from the application via one of its out parameters exceeds the property’s value, TestComplete treats the returned string as a null one.


Sub StringLengthDemo
Dim aString
  aString="Some text"
  Log.Message("The string is " & aqString.GetLength(aString) & " character(s) long.")
  Log.Message("The string is " & Len(aString) & " character(s) long.")

Concatenating strings

The operation that forms a string out of several others is called concatenation. The object has special method that perform this operation. In VBScript the concatenation is performed both by plus (+) and by ampersand (&) operators. The plus operator is intended to perform addition, but if both operators are strings, then string concatenation occurs. However it is more convenient to use the ampersand operator since it does not require a preliminary conversion to a string type.

This sample code shows how to make a string out of several substrings:


Sub ConcatenationDemo
Dim Str1
  Str1 = "String No 1 "
  Log.Message(aqString.Concat(Str1, "String No 2"))
  Log.Message(Str1 + "String No 2 " + "String No " + aqConvert.IntToStr(3))
  Log.Message(Str1 & "String No 2 " & "String No " & 3)

Comparing strings

String comparison is widely used during testing. Generally, a test procedure obtains textual data (user input, file contents, property values and so on) and then compares it with the expected data. That is why both TestComplete and VBScript have their own methods to compare one string value with another. These methods are: and .

The method has three parameters: two of them, String 1 and String2, specify the strings to be compared; the third parameter (CaseSensitive) defines whether the comparison should be case-sensitive or not.

Similarly, VBScript's function has two mandatory parameters, Str1 and Str2, that define the compared strings, and one optional parameter, CompType, that specifies the comparison type. The CompType parameter can accept the following values: (or ), and (or ). means binary case-sensitive comparison. means case-insensitive comparison. The default type is . The function result is -1 if Str1 is less than Str2, 1 if Str1 is greater than Str2 and they equal 0 if the strings are the same.

Both methods can compare strings holding specific national symbols, for example characters with diacritical marks ( , , and others).

The code below demonstrates how to use both methods:

Accessing individual character of a string

The VBScript scripting language has no data type that can be used to store single symbols. However, this is not a problem, since the string type can hold both a series of characters and individual characters. Moreover, you can extract a single character from a string using the method and VBScript’s function. The latter retrieves the given number of characters starting from the specified position. Note however that the VBScript function uses 1-based indexes, whereas the method uses zero-based indexes. The sample routine below demonstrates how to use both of these routines. It posts text to TestComplete log in two different ways: as a whole string and by a single letter.


Sub StringByLetter
Dim aString, i
  aString = "Per aspera ad astra"
  Log.Message("The string is : " & aString)
  Log.Message("And now this text letter by letter using aqString.GetChar:")
For i = 0 To aqString.GetLength(aString)-1
    Log.Message(aqString.GetChar(aString, i))
  Log.Message("And now this text letter by letter using Mid function:")
For i = 1 To Len(aString)
    Log.Message(Mid(aString, i, 1))

Searching for characters and substrings

One of the most common tasks that one has to perform when working with string values is determining whether specific text is part of a string. To perform such tasks, the object has the method. If the specified substring was found, the method returns the number of the first occurrence of the substring within the source string. If the specified substring was not found, the method returns -1:

You can also get the position where the specified substring occurs using the VBScript functions and . They both return the initial position (from 1) of the first substring match, but the first one searches from left to right, while the other from right to left. If the substring was found, the functions return the initial position of the first substring match. If no occurrences were found, they return 0. The code below demonstrates how to use the function:


Sub StringOccurrenceDemo
Dim aString, aSubString, Res

  aString = "Per aspera ad astra"
  aSubString = "astra"
  Res = aqString.Find(aString, aSubString)
If Res <> -1 Then
    Log.Message("A substring '" & aSubString & "' was found in string '" & aString & "' at position " & Res)
    Log.Message("There are no occurrences of '" & aSubString & "' in '" & aString & "'")


Sub TextPosDemo
Dim aString, aSubString, findpos

  aString = "Per aspera ad astra"
  aSubString = "astra"
  findpos = InStr(aString, aSubString)
If findpos <> 0 Then
    Log.Message("A substring '" & aSubString & "' was found at position " & findpos)
    Log.Message("There are no occurrences of '" & aSubString & "' in '" & aString & "'")

Getting a substring

VBScript has several methods that allow you to extract a substring out of a string. They are and . These methods vary in how the extracted substring is defined.

Function returns a text fragment that starts at the beginning of the given string and has the specified length. Function does a similar action, but it gets the last fragment of the given string. If the fragment’s length is greater than the length of the whole string, then the entire string is returned. Negative length values are not allowed, zero-length returns an empty string.

Function returns a text fragment that starts at a given position and has a specified length. The length parameter is optional, and if it is omitted then the resulting substring continues up to the end of the source string.

The object also has a similar method, that returns a substring that starts from the specified position and has the given length. However, this method requires all tree parameters, and position numbers are zero-based.

The sample code below demonstrates how to use these functions:


Splitting strings

Sometimes it is required to make several strings out of a single string. This operation splits a string into substrings. It can be performed by VBScript's native function called . This routine searches the string for a delimiter character, separates the string and returns an array holding the constituent strings. If the delimiter is omitted, then the space character is assumed as a delimiter. Also you can constrain the maximum array length with the third parameter and set the comparison method with the forth. They are not obligatory and can be omitted. The same method can be used to split a string onto substrings, sentences and even separate words; it all depends on the specified delimiter. The first sample routine below uses a space character as a delimiter to extract words out of a string, and the second routine splits the string by line breaks:

TestComplete has a similar method called aqString.GetListItem. It extracts a substring with the specified index from the input string. It was designed to read items from a string list, see Working with string lists for more information. However, it allows you to redefine the delimiter characters and, like the method, it can be used to get sentences, single words and so on.



Sub SplitDemo3
Dim s, prevSep

    s = "Better late than never but better never late."
' Assign list separator to space character
    prevSep = aqString.ListSeparator
    aqString.ListSeparator = " "
' Split by spaces
    Log.Message("There are " & aqString.GetListLength(s) & " words in a string")
    Log.Message("The first word is: " & aqString.GetListItem(s, 0))
' Restore previous separator
    aqString.ListSeparator = prevSep

Removing extra spaces from a string

The object has a special routine, , that excludes leading and trailing spaces (or both) from a string. VBScript has also the and functions that exclude, leading, trailing and both leading and trailing spaces from the input string. Generally, all these methods are used to remove unnecessary spaces at the beginning or at the end of strings obtained from the user input.

Another function that can be useful when handling user input strings is excluding extra inner spaces out of the string. This function seems to be similar to , but the latter only removes spaces at the beginning or end of the string and does not affect the spaces inside the string. The general idea of the function is for the string to be parsed into separate words and then a new string is constructed. The new string consists of the same words but is separated with a single space between words.


Sub TrimDemo
Dim str
  str="  Hallo  "

  Log.Message("'" & aqString.Trim(str, aqString.stLeading) & "'") 'Posts 'Hallo  '
  Log.Message("'" & aqString.Trim(str, aqString.stTrailing) & "'") 'Posts '  Hallo'
  Log.Message("'" & aqString.Trim(str, aqString.stAll) & "'") 'Posts 'Hallo'

  Log.Message("'" & LTrim(str) & "'") ' Posts 'Hallo  '
  Log.Message("'" & RTrim(str) & "'") ' Posts '  Hallo'
  Log.Message("'" & Trim(str) & "'") ' Posts 'Hallo'


Function TrimInner(Str)
Dim WordArray, i
    WordArray = Split(Str)
    Str = ""
For i = 0 To UBound(WordArray)
If WordArray(i) <> "" Then Str = Str & WordArray(i) & " "
    TrimInner = Trim(Str)

'An example of how to use this function
Sub TrimInnerDemo
  Log.Message(TrimInner("Follow the     white rabbit"))

Replacing characters and substrings

Quite often we need to find and replace a character or substring within a string. There are two ways to do this: by using the method or by using the method of a object.

The object method is much easier to use. It can be used when you need to change a certain character or string. It allows you to set whether the search should be case-sensitive or not. Here is an example of how to use this method:

The method is a little more complicated, but it offers more flexibility. You can not only change a definite character or string, but all fragments matching the specified regular expression pattern. However you have to create an instance of the object and set the pattern before replacing. The regular expression pattern is enclosed in double quotation marks ("). Additionally you can specify the following Boolean flags that affect the search procedure: - performs a global search for all occurrences of a pattern, - searches regardless of the letter case and - performs a multi-line search. For a full description of how to use regular expressions, refer to the Introduction to Regular Expressions article in the MSDN library.

The first sample demonstrates how to change a definite string using the method.

The second example shows how to replace a substring with alternative parts. The patterns of alternative parts are separated by pipe characters (" | "). For instance in the sample below the "ht(ml|m)" pattern matches both html and htm:

Furthermore, using regular expressions you can search for the text fragments that match the specified format. In the next sample, all dates written in the DD/MM/YYYY format are substituted with the Some Date string. This operation can be useful, for example, when comparing two reports that contain the generation date.


Sub StringReplaceDemo
Dim str
  str = "Hi, Bob. Have you seen Bob Robbinson?"

  str = aqString.Replace(str, "Bob", "Jack")


Sub RegExReplaceDemo1
Dim str, re
  str = "Hi, Bob. Have you seen Bob Robbinson?"
' Create RegExp instance.
Set re = New RegExp
' Define regular expression pattern
  re.Pattern = "Bob"
' Set global search flag
  re.Global = True
' Perform replace operation
  str = re.Replace(str, "Jack")


Sub RegExReplaceDemo2
Dim str, re
  str = "The html is widely used in Internet. The HTM file is a text file with tags."
' Create RegExp instance.
Set re = New RegExp
' Define regular expression pattern.
  re.Pattern = "ht(ml|m)"
' Set global search flag
  re.Global = True
' Set ignore letter case flag
  re.IgnoreCase = True
' Perform replace operation
  str = re.Replace(str, "hypertext markup language")


Sub RegExReplaceDemo3
Dim str, re
  str = "Date of report: 30/04/2005."
' Create RegExp instance.
Set re = New RegExp
' Define regular expression pattern.
  re.Pattern = "\d{1,2}.\d{1,2}.\d{2,4}"
' Set global search flag
  re.Global = True
' Perform replace operation
  str = re.Replace(str, "Some Date")

Changing the letter case

A string can contain both uppercase and lowercase letters. The TestComplete object and the native object have methods that convert uppercase letters to lowercase and vice versa. They are: and .

The code below demonstrates how all of these methods are applied.


Sub LetterCaseDemo
Dim str
  str = "The word 'Champagne' is of French origin"

' Converting to lower case

' Converting to upper case

Working with string lists

Some scripting objects, generally, controls like ListBoxes, ComboBoxes and Memos, return information about their state or contents as string lists. Individual data elements (or items) in this list are separated by commas, line breaks, carriage returns or some other delimiter characters.

The object has a number of specific methods (, , , and ) that are used to work with such lists. and add an item to or remove if from the list respectively. The method retrieves the item with the given index, and assigns a new value to the given item. The method returns the total number of items in the string list.

The symbol that is used as the separator between list items is defined by the property. By default, the list separator is a pipe (|), but it can also be a comma, column, line break, carriage return, tabulation, and any other printable and non-printable character, or even several characters.

Here is sample code that demonstrates how to work with the string lists returned by scripting objects.


See Also

Working With Strings
aqString Object
aqConvert Object

Last month, I discussed three basic syntax elements: variables, constants, and subtypes. However, I intentionally didn't discuss an important subtype: Array. This month, I take a close look at what Array variables, or simply arrays, are and how you can create, fill, resize, traverse, erase, split, and join them. I also cover multidimensional and nested arrays.

Related:Understanding VBScript: Operators

Arrays in VBScript

Unlike all the other subtypes I showed you last month, an array can hold more than one value. An array lets you address many data values through the same variable. Think of an array as a list (e.g., a list of usernames). You reference each item in this list with a common name and index number. The common name is the name of the array variable. The common name typically includes the prefix arr to denote that the variable contains data of the subtype Array. The index number is an integer subscript that denotes an item's relative location in the list. The indexes always increment sequentially, starting from 0. For example, if an array has three items, the indexes are 0, 1, and 2. The 0 index represents the first position, the 1 index represents the second position, and the 2 index represents the third position in the array.

You can create two types of arrays: static and dynamic. Static arrays stay a fixed size throughout their lifetime—that is, the index size remains constant. Thus, when you create a static array, you must know how many items the array will contain throughout its lifetime. If you don't know this information or you know that the array's index size will change, you need to create a dynamic array. Dynamic arrays don't have a fixed index size. You can increase or decrease the index size at any time.

Related:Sorting Arrays in VBScript

Creating Arrays

You can create arrays several ways, depending on whether they are static or dynamic. To create a static array, you use a Dim statement with the array's common name, such asDim arrGroc(2)

The number in parentheses specifies the maximum value of indexes in the array. The value of 2 denotes that the array's indexes range from 0 to 2, which means the array can contain up to three items. In other words, 2 is the array's upper bound. Arrays also have a lower bound. The lower bound of static (and dynamic) VBScript arrays is always 0 because arrays always start with the 0 index.

When you create a static array, the lower and the upper bound are 0 by default and the array is empty. Once you set a static array's upper bound, you can't change it because the static array's index size remains constant.

You can create a dynamic array in three ways:

  1. Use Dim without an upper bound.
  2. One way to create a dynamic array is to use a Dim statement in which you don't specify the array's upper bound. For example, to create the dynamic array arrUsers, you can use the statement Dim arrUsers()

    However, this array is uninitialized, which means you won't be able to use it until you set its size. To set the array's size, you use a ReDim statement to set the upper bound. For example, if you want to set an upper bound of 2 for arrUsers, you specify

    ReDim arrUsers(2)

    Although you set arrUsers' index size, the array is empty.

  3. Use ReDim alone.
  4. You can use ReDim without Dim to create a dynamic array that has an initial index size. For example, the code ReDim arrUsers(2)

    creates a dynamic array whose initial size is 3. The arrUsers array is empty.

    You typically use ReDim when you already know a useful initial size for the dynamic array. Using ReDim is more direct and saves you from adding an extra line of code.

  5. Use Array.
  6. You can use the Array function with Dim to simultaneously create and fill dynamic arrays. Dim creates and names the array, and Array fills its indexes. For example, to create arrUsers and assign the names of Mary, Bob, and Ann to its indexes, you use the code Dim arrUsers arrUsers = Array("Mary", "Bob", "Ann")

    Note that the code doesn't explicitly mention the size of the array. VBScript determines the array's size by the number of arguments (e.g., "Mary" is an argument) that you pass to the Array function. Keep in mind that the returned array contains only those items that you pass as arguments.

    Table 1 on the Win32 Scripting Journal Web site summarizes the options for creating dynamic and static arrays. Because the table mentions details such as whether you need to fill the array, you can use it as a quick reference guide.

Filling Arrays

If you don't use the Array function to create an array, the new array will be empty. To fill dynamic and static arrays, you assign items to the indexes in the following format:arrGroc(0) = "bread" arrGroc(1) = "cereal" arrGroc(2) = "milk"

In this case, the value in the parentheses after the common name isn't the array's upper bound but rather the particular index that you're filling. For example, you're filling the 0 index with the "bread" data value. Figure 1 graphically depicts the filled arrGroc static array.

The items you're assigning to the arrGroc indexes are in quotation marks because the data's subtype is String. In this case, the array's indexes contain homogeneous data (i.e., data with the same subtype). An array's indexes can also contain heterogeneous data (i.e., data with different subtypes).

You can choose not to fill an index. If you leave an index empty, the array's index positions don't change. For example, if you leave the 0 index empty, it still remains in the first position.

Although leaving an index empty doesn't result in an error, assigning an item to an inappropriate index does. For example, in arrGroc, if you specify either of these lines

arrGroc(-1) = "fruit" arrGroc(3) = "vegetables"

you'll get an error message when you run the code. Using the -1 index produces an error because indexes always start from 0. You can't use negative indexes. The 3 index produces an error because you declared arrGroc as an array with an upper bound of 2. You can't use an index that exceeds the upper bound that you previously set.

To use an array's values, you can use the array's common name and the index of interest. For example, you can use the VBScript's MsgBox function to display an item in a dialog box. If you want to find the item in the first position of the arrGroc array, you use the code

MsgBox arrGroc(0)

which prompts MsgBox to display the result of "bread".

If you want to find out how many indexes an array contains, you can use VBScript's LBound and UBound functions, which return the lower and upper bounds, respectively, for a given array. To use these functions, you specify either LBound or Ubound, followed by the array's common name in parentheses. For example, if you want to display the lower and upper bound of arrGroc, you specify

MsgBox LBound(arrGroc) MsgBox UBound(arrGroc)

The result of MsgBox LBound is 0. The result of MsgBox UBound is 2.

Resizing Arrays

When you use the Array function to create and fill a dynamic array, you must list all the items that the array currently contains. Thus, for this dynamic array to be useful in a real-world context, you must resize it as soon as you need to use it.

At any point in a script, you can use the ReDim statement to change a dynamic array's size or to initially set the size if you create an uninitialized dynamic array. For example, if you use the code

Dim arrUsers()

to create an uninitialized dynamic array at the beginning of your script, you can later set the array's size to 4 by specifying

ReDim arrUsers(3)

You can also use ReDim to resize an array to a smaller dimension (e.g., go from an index size of 11 to 5). You can resize an array as many times as you want.

Whether the new index size is smaller or larger, ReDim reallocates the original array's memory block to the new sized array, which means you lose all information about the original array's indexes. For example, suppose you create arrUsers, set the initial size to 4, assign the 0 index to the username "Mary", and use MsgBox to display the item that the 0 index represents:

Dim arrUsers() ReDim arrUsers(3) arrUsers(0) = "Mary" MsgBox arrUsers(0)

At this point, MsgBox displays the result "Mary". However, if you resize arrUsers to 6 and again use MsgBox to display the item that the 0 index represents

ReDim arrUsers(5) MsgBox arrUsers(0)

the result is an empty display. Resizing the array to 6 causes the loss of all the original array's data.

Fortunately, you can prevent data loss by specifying the keyword Preserve after ReDim. When you increase an array's size, Preserve saves all array data. When you decrease an array's size, Preserve limits the loss of data to only those items no longer represented by the new indexes. For example, the code

ReDim Preserve arrUsers(5)

resizes arrUsers to 6 items and preserves all the existing items represented by indexes 0 through 5. So, if you apply Preserve to the previous example, the second use of MsgBox returns the name "Mary" rather than an empty display.

Filling Resized Arrays

When you increase a dynamic array's index size, you need to fill the new indexes. Although you use the familiar technique of assigning an item to each new index, you must indirectly reference that new index. Directly referencing it (i.e., using a constant value) defeats the purpose of dynamic arrays.

For example, suppose you use the Array function to create and fill arrUsers with "Mary", "Bob", and "Ann". You then decide to add "John" to arrUsers. If you specify

Dim arrUsers arrUsers = Array("Mary", "Bob", "Ann") ReDim Preserve arrUsers(3) arrUsers(3) = "John"

you're using a constant value (3) to set the array's new upper bound and index. A better approach is to use UBound to set the new upper bound and index:

Dim arrUsers arrUsers = Array("Mary", "Bob", "Ann") ReDim Preserve arrUsers(UBound(arrUsers) + 1) arrUsers(UBound(arrUsers)) = "John"

In the ReDim Preserve statement, UBound refers to the array's old size. You add a value of 1 to UBound because you're adding another index. You use UBound again to set the new index to "John". In this instance, UBound refers to the index number. You don't need to add 1 to UBound this time because the previous line already set arrUsers to the new value.

Traversing Arrays

With static arrays, you always know the upper bound. Thus, you can easily traverse a static array because you know exactly how many steps you need to take to iterate through all its indexes. For example, suppose you want to display the items in the static arrayDim arrGroc(2)

Instead of using three MsgBox functions

MsgBox arrGroc(0) = "bread" MsgBox arrGroc(1) = "cereal" MsgBox arrGroc(2) = "milk"

to display each item in a separate message box, you can use one For...Next statement to display all the items in one message box. For...Next repeats a group of statements (in this case, the MsgBox line) a specified number of times. You use the lower and upper bounds to specify that number:

For i = 0 to 2 MsgBox arrGroc(i) Next

For...Next traverses arrGroc in three steps. The letter i is a variable index that represents the index MsgBox is displaying at any particular step. In other words, i represents the 0 index in the first step, the 1 index in the second step, and the 2 index in the third step.

Traversing dynamic arrays isn't as simple because you don't know the upper bound. To traverse dynamic arrays (and even static arrays), you can use LBound and UBound to dynamically return the lower and upper bounds for a given array. So, instead of specifying an array's lower and upper bounds, you use LBound and UBound:

For i = LBound(arrUsers) to UBound(arrUsers) MsgBox arrUsers(i) Next

Another technique you can use to traverse dynamic and static arrays applies VBScript's For Each...Next statement, which repeats a group of statements for each item in an array. Because this technique doesn't use index-based navigation, you don't have to deal with lower and upper bounds. This technique assigns all the items in an array to the elem variable. Once the items are in the variable, you can manipulate them. For example, to display all the items in arrUsers, you use the code

For Each elem In arrUsers MsgBox elem Next

Erasing Arrays

If you need to free an array, you use the Erase statement. For static arrays, Erase doesn't change an array's lower and upper bounds; it erases only the items' content. Erase reinitializes an array's items by setting the array to the null value for the specified subtype (e.g., the empty string for strings, 0 for numbers, Nothing for objects). For example, if you run the code in Listing 1 that erases the static array, the message box displays "0 ­ 2". Thus, Erase didn't change the bounds. However, if you display the content of any item, you get only empty strings.

For dynamic arrays, Erase releases an array's allocated memory. For example, if you run the code in Listing 1 that erases the dynamic array, you get an error because Erase releases all the memory that refers to the array. The variable still exists, but the information about the bounds doesn't. Erase returns a dynamic array to the state immediately after its declaration when its bounds are uninitialized and unusable.

Splitting and Joining Array Indexes

VBScript's Split and Join functions let you split and join the values of indexes in a static or dynamic array. The Split function uses a delimiter to separate a string into substrings and assigns those substrings to an array's indexes. You specify the string and delimiter as arguments to the Split function. For example, if you pass the arguments of "One,Two,Three" and "," to the Split function in code such asDim arrNumbers arrNumbers = split("One,Two,Three", ",")

the function returns an array in which the 0 index represents "One", the 1 index represents "Two", and the 2 index represents "Three".

The Join function performs the reverse task. It combines the substrings that each array index contains into one string and assigns that string to a String variable (not an array—the prefix str denotes a variable whose subtype is String). For example, the code

Dim strNumbers strNumbers = join(arrNumbers, ",")

combines the substrings in the arrList indexes and assigns the result—the original string "One,Two,Three"—to strNumbers.

Using Multidimensional Arrays

All the arrays I've shown you so far contain one list of data, or dimension. However, arrays can contain more than one list of data. In other words, arrays can be multidimensional.

Figure 2 provides a graphical view of a two-dimensional array. Similar to a table, a 2-D array has a specific number of rows and columns. The first dimension forms the rows, and the second dimension forms the columns. Each cell represents an index.

You create static and dynamic 2-D arrays the same way you create 1-D arrays, except in 2-D arrays you have two upper bound values in the parentheses: the upper bound of the first dimension followed by the upper bound of the second dimension. For example, to create the 2-D static array, arrMultiGroc, in Figure 2, you specify

Dim arrMultiGroc(3,2)

If you create a dynamic multidimensional array and you want to resize it with the ReDim Preserve statement, by design you can modify only the last dimension of the array. (If you use ReDim without Preserve, you can modify any dimension.) For example, suppose you create a dynamic 2-D array, arrMultiUsers, with the code

ReDim arrMultiUsers(3,2)

and later you want to resize it, preserving the original array indexes. If you specify

ReDim Preserve arrMultiUsers(2,2)

you'll get an error message because you changed the first dimension. If you specify

ReDim Preserve arrMultiUsers(3,4)

the code will successfully execute. If you specify

ReDim arrMultiUsers(2,2)

the code will execute, but you'll lose all the original index data because you didn't specify Preserve.

You manipulate the indexes of static and dynamic 2-D arrays the same way you manipulate the indexes of their 1-D counterparts. However, you must include the indexes of first and second dimensions, respectively, in parentheses. For example, to fill and display the 2,1 index of arrMultiGroc, you specify

arrMultiGroc(2,1) = "orange" MsgBox arrMultiGroc(2,1)

VBScript supports up to 60 dimensions. However, you'll probably never use more than three dimensions. If you're curious about what a 3-D array looks like, check out Figure A on the Win32 Scripting Journal Web site.

Using Nested Arrays

You can nest arrays, which means you fill an array's index with an existing array. Nested arrays aren't the same as multidimensional arrays, as Figure 3 shows. A multidimensional array has a somewhat flat structure that contains only one array. A nested array has a hierarchical structure that contains two or more independent arrays. The nested array in Figure 3 has three independent arrays. The arrChild2 array is nested in the arrChild1 array, which is nested in the main array.

Listing 2 shows how to nest an array. You first create and fill the array that you'll nest inside another array. In this case, that array is arrChild. You then assign arrChild as the third item (the 2 index) of the arrMain array. Note that arrMain contains heterogeneous data values.

The last line in Listing 2 displays the value of the index you just filled. As this line shows, you must use a special syntax to manipulate the items in a nested array. The code to address the first item of the child array is


Because a nested array isn't a multidimensional array, you can't use two conjunct indexes such as (2,0). Actually, you're just addressing the first item of a 1-D array called arrMain(2).

An Important Tool

Arrays are an important part of the VBScript language. Once you learn about VBScript operators, statements, and subroutines (which I'll cover in a future column), you can easily incorporate arrays into your scripts. (If you're already familiar with all aspects of VBScript, check out the Web exclusive sidebar "Using VBScript Arrays in Scripts." This sidebar provides an example of using VBScript arrays in a script and discusses why you might encounter problems if you use both VBScript and JScript arrays in a script. Go to the Win32 Scripting Journal Web site, and select View Current Issue in the Subscriber Areas. Select Using VBScript Arrays in Scripts from the July table of contents.)

Arrays aren't only easy to use but also powerful. Some of their many advantages include the following:

  • You can use one variable to handle many data values, which lets you efficiently process numerous data values.
  • You can easily enumerate the values in an array, which greatly facilitates applying the same code to a group of related data.
  • Arrays can have more than one dimension, which helps considerably to model complex data.
  • You can nest arrays, which lets you render not only tabular data sets but also hierarchical data sets

Learn more:Arrays and Temporary Files

TAGS: Software Development

0 Replies to “Wincc Text List Assignment Index”

Lascia un Commento

L'indirizzo email non verrà pubblicato. I campi obbligatori sono contrassegnati *