Get this lesson’s code from my GitHub.
This one’s pretty easy or self-explanatory, but it still deserved its own section. You can do a lot of cool things with strings if you understand the different operators and how you can use them in combination with if-then-else statements and comparing strings.
It is a good idea to keep short lines when you code. To continue onto the next line in VBA, you type a space followed by an underscore, then enter to go to the next line. You may indent after that however you like for looks, but those three characters need to be typed 1, 2, 3; space, underscore, enter; just as I described.
Math operators include all the arithmetic symbols, such as:
' > < + - * / <> = ' greater than, less than, plus, minus, 'times, divide, not equal, equal
Here are some examples of how we use them. I’ll be using if-then-else statements, which we have not covered yet, to demonstrate:
Function fFunction() dim x as integer x = 3 If x < 4 and x >= 0 Then Debug.Print x Elseif x > 5 Then Debug.Print "x is too big!" Else End if End Function
The following makes use of some of the operators as well as showing how to extend a piece of code to the next line.
Function fFunction() 'declare variables dim sValue1 as string dim sValue2 as string 'assign value to them sValue1 = "Hello " sValue2 = "World" 'use of logical operators: If sValue1 = "Hello " and sValue2 = "World" Then Debug.Print sValue1 & sValue2 Elseif sValue1 = "Hello " or sValue2 = "World" Then Debug.Print sValue1 & sValue2 Else Debug.Print sValue1 & "!" End If If not sValue1 = "Hello" Then Debug.Print "I didn't say hello. i said, " & _ sValue1 & "!" End Function
Concatenate strings with ‘ &’ like in this example. Also shown in this example is “Chr(32)”, which is called an ASCII code, which represents a single character. We will be using these moderately throughout, so I have demonstrated it here. You can find a table listing all characters and their ASCII numbers here.
Function fFunction() 'declare variables dim sValue1 as string dim sValue2 as string dim sValue3 as string 'assign value to them sValue1 = "Hello" sValue2 = "World" sValue3 = sValue1 & Chr(32) & sValue2 _ & Chr(33) 'hit Ctrl+G to see debug window. 'Prints in debug window '"Hello World!" without the quotes. Debug.Print sValue3 End Function
We’ll discuss these in more detail as they come up in the functions I’ll be showing you how to write. Next up, we’ll be discussing DAO recordsets.
**While we have made every effort to provide accurate information, A Quo Co. and Erica L. Ingram assume no responsibility or liability for any errors or omissions in the content of this blog. The information contained in this blog is provided on an “as is” basis with no guarantees of completeness, accuracy, usefulness, or timeliness.