Vba Programming Basics

To ensure that a string has desired length, you can use the Len function to determine the number of characters in the string. Based upon the value returned by the built-in VBA function, you determine whether you can concatenate the strings without VBA truncating them. For example, if each string you want to join is ten characters in length, you must make the variable that receives the concatenated string at least 20 characters in length, or VBA truncates the string.

If you check the length of a fixed-length variable, it always returns the declared string length, even if the number of characters saved in the string is less than the declared length, as illustrated in the following examples.


Dim StringTest1 As String * 15 StringTest1 = "SampleString" Len(StringTest1)

In the above, the StringTest1 string variable has a fixed-length of 15 no matter what you add to the variable. When you add the string "SampleString" to the variable — even though the string only has 12 character — the Len function returns a value of 15.


Dim StringTest2 As String StringTest2 = "SampleString" Len(StringTest2)

The StringTest2 string variable has a variable length. When you add the string "SampleString" to the variable, the length of the variable adjusts to fit the string. Because the length of the string is 12 characters, the Len function returns a value of 12.

| File Edit View Insert Format Debug Run Tools a-HJiiilS«1"" ►!!■!£


Jd-Ins Window Help

Mlfftf | LI

0 0

Post a comment