MS-Access / Getting Started

Splitting Strings

You may need only a part of a string in your code. For example, say you have a two-figure reference number at the beginning of the string that you need to use elsewhere in your program, but you wish to show only the name:


To pull out the name only, you can use the Mid function:


This code will start at the third character and continue to the end of the string and place the result in the variable x, which will then contain the string "Martin". The Mid function has an optional length parameter so that you can specify the length of your substring. If you leave this out, you will get everything from your start point to the end of the string.

Note that in all these situations you can also use a variable that contains a string:



You can also use this function to extract the number portion of the string at the front:


This code will start at the first character and take the next two characters from the string and place them in the variable x, which will contain a string with the value of 12, although this is not actually a number but a string. VBA is quite forgiving-if you want to do further calculations with this, you do not need to change it back to a number.

However, if you are putting it back into a field in a table, you may need to change it to a number from a formatting point of view. You do this by using the Val function:

Dim iValue as Integer
iValue = Val("12")

The variable iValue will then be an actual number rather than a string.
VBA also includes Right and Left string functions. The Left function can also be used to separate the number 12:


The variable x will have the value 12.
If the Right function is used, x will have the value rd:


The Left and Right functions grab from the side of the string, as indicated by the function name.

VBA also contains functions to change the case of a string, as discussed next.

Changing the Appearance of Strings

UCase changes everything in the string to uppercase:


The variable x will have the value MARTIN.
LCase changes everything to lowercase:


The variable x will have the value martin.
In both of these examples, any nonletter characters such as numbers will be left as they are.

[Previous] [Contents] [Next]