Excel VBA
Introduction To VBA: Macros And Automation Part 1
Our First Macros
Defining Variables
Now that the fundamentals are covered, we will gloss over the steps previously defined, and focus on the new steps needed to expand our understanding of VBA!
What if now, instead of the “Hello World!” message, we wanted to change what the message box says when our button is pressed?
We can create a variable within our code, that we will then use to change our message.
Under the End Sub line, we will begin a new subroutine which we will call ExVariable.
This time, we will initialize a new variable, one we will call NewText, and it will be of the String data type.
To do this we must type out the following:
Dim NewText As String
This line states what we are creating a new variable whose data type is String.
The next step is to add a value to this variable, currently NewText is null and contains no information.
We will now assign the value of “You Are Excellent!” to the variable NewText by typing in the following:
NewText = “You Are Excellent!”
And as simply as that, the variable NewText now contains the phrase we chose.
The last step will be very similar to our first example, but instead of a text string, we will be calling our variable.
To have the message box display the contents of our variable, we type out the following:
MsgBox NewText
And now all that is left is to test our second macro!
Create a second button with the display text ‘Variable’, and assign it the ExVariable macro.
By pressing our new button we should see the message box appear with our new message inside.
Our next macro example will look at referencing cells from our workbook as inputs for our variables.