MOCKSTACKS
EN
Questions And Answers

More Tutorials









VBA String


A String represents a sequence of characters, and comes in two flavors:

Variable length


Dim Value As String

A variable length String allows appending and truncation and is stored in memory as a COM BSTR. This consists of a 4 byte unsigned integer that stores the length of the String in bytes followed by the string data itself as wide characters (2 bytes per character) and terminated with 2 null bytes. Thus, the maximum string length that can be handled by VBA is 2,147,483,647 characters.

The internal pointer to the structure (retrievable by the StrPtr() function) points to the memory location of the data, not the length prefix. This means that a VBA String can be passed directly API functions that require a pointer to a character array.

Because the length can change, VBA reallocates memory for a String every time the variable is assigned to, which can impose performance penalties for procedures that alter them repeatedly.

Fixed length


Dim Value As String * 1024 'Declares a fixed length string of 1024 characters.

Fixed length strings are allocated 2 bytes for each character and are stored in memory as a simple byte array. Once allocated, the length of the String is immutable. They are not null terminated in memory, so a string that fills the memory allocated with non-null characters is unsuitable for passing to API functions expecting a null terminated string.

Fixed length strings carry over a legacy 16 bit index limitation, so can only be up to 65,535 characters in length. Attempting to assign a value longer than the available memory space will not result in a runtime error - instead the resulting value will simply be truncated:

Dim Foobar As String * 5
Foobar = "Foo" & "bar"
Debug.Print Foobar 'Prints "Fooba"

The casting function to convert to a String of either type is CStr().

Conclusion

In this page (written and validated by ) you learned about VBA String . What's Next? If you are interested in completing VBA tutorial, your next topic will be learning about: VBA Naming Conventions.



Incorrect info or code snippet? We take very seriously the accuracy of the information provided on our website. We also make sure to test all snippets and examples provided for each section. If you find any incorrect information, please send us an email about the issue: mockstacks@gmail.com.


Share On:


Mockstacks was launched to help beginners learn programming languages; the site is optimized with no Ads as, Ads might slow down the performance. We also don't track any personal information; we also don't collect any kind of data unless the user provided us a corrected information. Almost all examples have been tested. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. By using Mockstacks.com, you agree to have read and accepted our terms of use, cookies and privacy policy.