40
Chapter 1
•
Manipulating Strings
4
How do you decide which type of string to use? Dynamic strings require a bit
more processing effort from VBA and are, accordingly, a bit slower to use. On the
other hand, you make up the time by not needing to use the Trim function to remove
excess space every time you use the string. As you’ll see by working through the
examples in this chapter, we use fixed-length strings only when it’s necessary.
When working with a single character at a time, it makes sense to use a fixed-length
string declared to contain a single character. Because you know you’ll always
have only a single character in the string, you’ll never need to trim off excess
space. You get the benefits of a fixed-length string without the extra overhead.
Unicode versus ANSI
The 32-bit Windows “universe” supports two character storage mechanisms:
ANSI and Unicode. The ANSI storage standard uses a single byte for every char-
acter, with only 256 different characters allowed in any ANSI character set. If you
want to display characters from a different set of 256, you must load a separate
code page. This limitation makes it difficult to create internationalized applica-
tions. Windows 95 and Windows 98 use this approach for compatibility with pre-
vious versions of Windows. The Unicode standard allows for 65,536 characters,
each taking up two bytes. The Unicode character set includes just about all the
known written characters and ideograms in a single entity. In this way, an appli-
cation that embraces the Unicode standard can support (once its text has been
translated) just about any written language. Windows NT and Windows 2000
support the Unicode standard.
No matter what operating system you’re using, VBA stores strings internally in
Unicode format. That is, every character takes up two bytes of space. When VBA
needs to communicate with Windows 95 or Windows 98 (when you include Win-
dows API calls in your code, for example), it must first convert strings to ANSI
format. This happens automatically when you use the ANSI version of a Win-
dows API call that involves strings. The only other time you’ll care about how
VBA stores strings is when you want to convert a string into an array of bytes—a
useful technique that we’ll take advantage of a few times in this chapter. In this
case, a string containing five characters becomes an array of bytes containing ten
bytes. For example, a string containing the text
Hello
would contain the following
ten bytes, once converted to a byte array:
72 0 101 0 108 0 108 0 111 0