You are viewing an old version of this page. View the current version.

Compare with Current View Page History

« Previous Version 30 Next »


The tutorials on VBA will include both videos and text. If you have feedback on either, please leave a post on our Forum or send us a mail.

Page content

Hello World

Our first encouter with VBA will be to display the familiar "Hello World" message using a button.

  1. Choose the "Developer" tab and open the VBA editor. If you don't locate the VBA editor, follow this guide. The following window will then open.
  2. To write our first macro, choose "Instert" -> "Module".

  3. First, we will make a Sub procedure that we may later add to our button. All Sub procedures have to begin with Sub and end with End Sub. A Sub can not return a value, and may be compared with a program in other programming languages, where as a function is an alternative. We then call the MsgBox function to create a new window displaying our message.


  4. Lets now return to our Excel sheet to add the button. The insert button feature is shown in the image below.

    Tips: To align the size of the button with existing cells, hold down ALT while resizing. This applies to all sizings!


  5. A new window will open. Choose the "Hello World" macro we just created and click "OK".


  6. We may then rename our button by right-clicking on it and choosing "Edit text".



  7. Finally, we can test our macro by clicking on the button. A window displaying the message "Hello World!" should then open.
    If it does, congratulations! You have just made your first macro using VBA.

Operators


Comparison operators are used to compare expressions. They may return True, False or Null. Below is a table showing the basic logical operators in VBA.

OperatorExplanation (True if)
A < BA less than B
A < = BA less than or equal to B
A > BA greater than B
A > = BA greater than or equal to B
A = BA equal to B
A < > BA not equal to B

To learn when the compartion operators return Null, read the offical documentation on the comparison operators. Here, you will also find more detailed information regarding the actual comparisons done when using the operators. This includes outcome of comparing different variant types, such as a string and a double.

Let's look at some exampels:

Dim MyResult, Var1, Var2	' Variables are declared as type "Variant"
Dim str1 As String
Dim num1 As Integer

MyResult = (10 < 5)    		' Returns False.
MyResult = (1 <> 2)    		' Returns True.
MyResult = ("5" > "4")    	' Returns True.

MyResult = ("hi" > "hello") ' Returns True, since ("i" > "e").
MyResult = ("hi" > "Hi")    ' Returns True, since the ASCII values for lowercase letters are higher than for uppercase letters.


Var1 = 5: Var2 = Empty
MyResult = (Var1 > Var2)    ' Returns True, since "Empty" is evaluated as 0.

Var1 = 5: Var2 = Empty
MyResult = (Var1 > Var2)    ' Returns False, since "Empty" is evaluated as 0.

Var1 = 0: Var2 = Empty
MyResult = (Var1 = Var2)    ' Returns False, since "Empty" is evaluated as 0.


Var1 = "1": Var2 = 4
MyResult = (Var1 > Var2)    ' Returns True, since a "Variant of type string" is always greater than a "Variant of type numeric".

str1 = "1": num1 = 4
MyResult = (str1 > num1)	' Returns False, since the "string" may be converted to a number, thus using a numerical comparison.

str1 = "a": num1 = 4
MyResult = (str1 > num1)	' Returns an error of type "Type missmatch", this because the "string" can not be converted to a number.

As we can see, you may compare almost anything in VBA. Knowing what the outcome of each comparison is, will give you a great advantage when coding.



Explicit vs implicit variable declaration

When writing larger pieces of code, knowing the difference between explicit and implicit variable declaration may save you several hours of debugging.

Before we look at the different variable declarations, we need to establish the difference between the words explicit and implicit.

  • explicit is defined as: "stated clearly and in detail, leaving no room for confusion or doubt."
  • implicit is defined as: "implied, rather than expressly stated"

When coding in Visual Basic, you are by default not obligated to declare your variables before using them. This an example of an implicit variable declaration.

MyVariable = 10

When doing so, VBA will automatically declare it as a variant type, provided that the variable has not been declared before. This is a nice feature, but may cause trouble when writing larger scripts. Let's look at an example:

We have already written a lot of code using the variable "MyVariable". If we were to misspell "MyVariable" with "MyVaiable" once, VBA will think of it as a new variable, and declare it automatically, thus not informing us of our misspell.

MyVariable = 4
'We want to multiply MyVariable with 10
MyVaiable = MyVariable * 10

'... lots of code

'When we finally display MyVariable, thinking it equals 40
MsgBox MyVariable
'4 is displayed

To avoid this problem, we can use the Option Explicit Statement. It ensures that all variables must be explicitly declared by using the Dim, Private, Public, ReDim or Static statements. Otherwise, it will display an error at compile time.

If used, the "Option Explicit" statement must appear in a module before any procedures.

Option Explicit

Sub Example()

'Explicitly declaring MyVariable as an integer
Dim MyVariable As Integer

MyVariable = 4
'We want to multiply MyVariable with 10
MyVaiable = MyVariable * 10

'... lots of code

'When we finally display MyVariable, thinking it equals 40
MsgBox MyVariable
'4 is displayed

End Sub

Compiling the code above will result in the following error message.

If you want to make all your modules have the "Option Explicit" statement without having to remember to write it yourself, follow these instructions:

  1. In your VBA editor, go to "Tools" → "Options".


  2. Tick the "Require Variable Declaration" box. Click "OK".

Format function

The Format function is a helpful tool when formatting strings to your preference. Since Microsoft already has made a really in-depth explanation including some examples, we have chosen to only show you some additional examples here.

Format function examples
myVar = Format(50000)
'myVar is now equal to the String "50000".

myVar = Format(50000, "Currency")
'myVar is now equal to the String "kr 50 000,00".

myVar = Format(50000, "#,##0.0")
'myVar is now equal to the String "50,000.0".

myVar = Format(0.88, "Percent")
'myVar is now equal to the String "88.00%".

myVar = Format(0.88, "0.0")
'myVar is now equal to the String "0.9".

myVar = Format("Ola Nordmann", ">")
'myVar is now equal to the String "OLA NORDMANN".

myVar = Format("Ola Nordmann", "<")
'myVar is now equal to the String "ola nordmann".

myVar = Format("123456789", "@@@-@@@-@@@")
'myVar is now equal to the String "123-456-789".


  • No labels