Tag Archives: VBA

Working with Arrays in Excel VBA VIDEO

Arrays are the selection of multiple columns and rows in Excel. In this video, we will learn how to manipulate an array with simple multiplication. Learning about this in isolation is not highly applicable. However, what is learned here is important for more practical actions when using VBA.

ad

Creating Local Arrays in Excel VBA

Local arrays are arrays that are stored in Excel but are not necessarily seen in the worksheet. We will now look at two ways in which we can create local arrays in Excel using VBA. These two ways are

  • Hardcoded by the developer
  • Inputted by the user

Hardcoded

Below is an image of what we want to create.

The numbers in green are for labeling the rows and columns. What is really going into VBA is the numbers in black. For example row 1 column 1 contains the number 10, row 1 column 2 contains 12, etc. To do this we need to create a subroutine that makes an array. Below is the code

Option Base 1
Sub newArray()
Dim myArray(2,2) As Integer
myArray(1,1) = 1
myArray(1,2) = 2
myArray(2,1) = 3
myArray(2,2) = 4
MsgBox myArray(1,1)

Here is what we did

  1. Line 1 we set an option called Options Base 1. If we do not o this, VBA adds an extra column to the array called 0. THis is not wrong but can cause problem later if you are not aware this can happen.
  2. Line 2-3 we intitate the sub routine and Dim the array with a 2×2 strcuture
  3. Line 4-6 are used to set each cell in the array to a specific value.
  4. Line 7 outputs the value in Row 1 column 1 as proof the subroutie worked

Below is the output

The one in the message box is from row 1 column 1 of the array. The output below is from the locals window in the developer.

This image provides evidence that the array works. You can see that each position of the array has a stored value.

User Inputted Array

It is also possible for users to input values into an array. Doing this requires input boxes and the use of nested for loops, both of these were discussed in a prior post. Below is the code.

Option Base 1
Sub makeArray()
Dim myArray(2,2) As Integer
Dim i As Integer, j As Integer
For i = 1 To 2
	For j = 1 To 2
		myArray(i,j)=InputBox("Enter number for element " & i & "," & j)
		Next j
	next i
End Sub

The first 4 lines are the same as the last code. Line 5 is where the for loop begins. The purpose of the for loop is to go across each column then skip down to the next row. The input box asks the user for a number as shown below

If you put the same numbers into the input box as in the original array you will see the following in the locals window.

Conclusion

Local arrays can be useful when combined with other ideas in Excel VBA. This will be covered in a future post

Intro to Arrays in VBA

Arrays are simply the use of multiple rows and columns in Excel. Generally, this happens through selecting them. The benefit of arrays is that you can perform calculations on several rows and columns of data at once. Below is a picture of an array.

The Purpose

ad

Our purpose is going to be to take an array and multiple all the values by 3. In order to do this, we will have to use nested for loops and learn some terminology.

The for loops are difficult to master if you are new to coding. However, what we need is for VBA to loop through all the rows and loop through all the columns completing the calculation we want. This is commonly done by labeling the rows as the letter “i” in coding and columns as the letter “j”. Below is a picture of what I have just said.

For the actually coding here are the variables we need to declare in our subroutine

  • i for rows
  • j for columns
  • nr for number of rows
  • nc for number of columns

We need to count the rows and columns so the for loop knows when to stop.

Below are the functions we will use

  • A function that counts the rows
  • A function that counts the columns
  • A function that selects the cells
  • Multiply by 3 the selected cells

Below is the actual code

Sub timesThree()
Dim i As Integer, j As Integer, nr As Integer, nc As Integer
nr = Selection.Rows.Count
nc = Selection.Columns.Count
For i = 1 To nr
    For j = 1 To nc
    Selection.Cells(i, j) = Selection.Cells(i, j) * 3
    Next j
Next i
End Sub

Here is what the code does

  1. Line one gives the subroutine a name
  2. Line 2 declares the variables
  3. Line 3 and 4 tell VBA to count the number of rows and columns
  4. Line 5-10 is the for loop. i and j are set to 1 initially and continue until whatever value nr and nc have. Whatever position the selected cell is at is multplied by three.

Below is a picture of the before and after effects of using this code on an array.

In the picture above you can see the array is 3×3 and selected. The code is to the right. In the bottom right you have the locals window which will provide information on the variables that are created. Below is the output

Here you can see that all the values in the array have been multiplied by three as planned. The highlighted yellow in the code indicates that we are at the end of the code and are ending the subroutine. The information in the locals window is hard to read but simply shares information on the values in the various variables that were created.

Conclusion

With this information, it is possible to create arrays and manipulate them in Excel VBA. As already mentioned, this information must be used in combination with other techniques to truly be useful for the average developer.

For Next Loops in Excel VBA

For Next loops are a type of count controlled loop in VBA. By count controlled it is meant that this loop is performed a certain number of times as determine by the criteria set by the developer. In this post, we are going to learn how to use For Next loops with functions and with Subroutines.

For Next Explained

Below is a high level overview of the behavior of For Next loops in a visual.

The For Next loop begins at i. This is normally one but it is flexible. In addition, the value normally increases by 1 also. Next, we have the loop it repeats until i reaches whatever the limit is. Often the limit is set by the number of rows or some other means and is generally called n in coding. The limit continues based on an if then statement. If i is less than the limit then it will increase by one and repeat the process. If i is greater than the limit then it will exit.

ad

One thing that is missing from this diagram that is also important is some sort of way to count how many times the For Next loop finds what the developer is looking for. This value is often set to c and increase by one each time through the code. This will make more sense in an actual example.

Code for Function

Below is the code for a function that uses a For Next loop. This function will check if out number is divisible by 4 or 7.

Function numberCheck(n As Integer) As Integer
Dim i As Integer, c As Integer
For i = 1 To n
    If i Mod 4 = 0 Or i Mod 7 = 0 Then
    c = c + 1
    End If
Next i
numberCheck = c
End Function

In the code above we are doing the following.

  1. Creating a function called “numberCheck) that sets n as our variable for the limit
  2. We dim the c and c variables
  3. Next, is our loop, i is set to 1 and will continue until n which is picked by the developer
  4. After this, is our If Then statement. If our number from n is divisible by 4 or 7 then the c value will go up 1.
  5. Then we repeat this process until we reach the end of n
  6. Exit function.

The image below shows this function in action.

The function is counting how many numbers between 1 and 16 are divisible by 4 or 7. The answer is 6.

Subroutine Code

We will now complete a similiar task with a subroutine. This time we want to count a selection of rows and see how many number 3s it has. Below is the code.

Sub CountThrees()
Dim nr As Integer, i As Integer, c As Integer
nr = Selection.Rows.Count
For i = 1 To nr
If Selection.Cells(i, 1) = 3 Then c = c + 1
Next i
MsgBox ("There are " & c & " threes in your selection.")
End Sub

This code does the following

  1. We give the subroutine the name “CountThrees”
  2. We dim nr for the number of rows, and we also dim i and c as in the previous example
  3. The for next loop is next and goes from 1 to the end of all the rows
  4. Inside the for next loop the if then statement looks at the cells that are selected in the Excel spreadsheet and searches for those that are the number for. Then these 3 are counted and saved in the c function
  5. Then the process repeats it’s self
  6. At the end, a message bx appears telling the user how many threes are found

Below is an image of this codes actions

Here is the data the subroutine will analyze. You can count for yourself that there are three 3 in this column

Below is the result

The image below shows what is happening in VBA

The image above comes from the locals window in VBA. You can see at the end of the four loop that we ten rows of data (nr) i was set to 11, which is greater than nr which cause the loop to exit. Lastly, c was set to three which indicates that there were 3 threes in the selection

Conclusion

For Next loops are another useful tool for VBA developers. They allow you to let the context of the code determine how many iterations the loop completes.

ElseIf Statements in Excel VBA VIDEO

ElesIf statements in VBA allow the developer to include multiple alternative actions within a subroutine or function. This allows for the code do execute goals that are more complex than just If-then statements. The video below addresses how to develop a function that includes Else-if statements.

Ad

Do Until Loops in Excel VBA

Do until Loops in VBA are for repeating a task until some criteria is met. How this is used can vary widely depending on what the developers goals are for implementing the loop in the first place. In this post, we will look at an example of the use of a general do loop. By general do loop we mean a loop that has no predetermine number of times it will run.

ad

Our goal is going to be to create a subroutine that ask the user for a number. This number will then be squared until it is greater than 2000. Once the number is larger than 2000, VBA will exit the loop and share the results with the user.

Below is a picture of how the Do loop is suppose to work.

As you can see the loop takes a number, squares it and then checks if the number is larger than 2000. If the number is larger than 2000 VBA exits the loop. If not, the new x value is the square of the old one and the process repeats.

Below is the code for completing this task in VBA

Sub squareLoop()
Dim x As Double, y As Double
x = InputBox("Enter your number")
Do
y=x*x
If y > 2000 Then Exit Do
x=y
Loop
MsgBox ("Your number is " & y)
End Sub

Here is what each line of code does.

  1. Line 1 declares the subroutine called “squareLoop”
  2. Line 2 we dim the two variables we need
  3. Line 3 is the code for creating the input box for the user and saves this information as our x variable
  4. Line 4 is the beginning of or do loop
  5. Line 5 is were we square our x variable and name it the y variable
  6. Next we have our if-then statement. If y is greater than 2000 than we exit the do loop
  7. In line 7 if our y value is not greater than 2000 than we save it as the new x value and return to the beginning of the loop in line 4-5
  8. Once we have a value greater than 2000 we skip to the bottom of the code and output a message box

The output is shown below

First Excel ask you for a number. For our example, we put the number 10.

Next, VBA squares the input number

10 * 10 is 100 which is not greater than 2000 so VBA goes through the loop again

The second time through are value is greater than 2000 so we get the message box with our value.

This is a relative simple process that has greater implications.

Conclusion

Do loops are another powerful tool you can implement in Excel VBA. The ability to automate repetitive task is valuable for saving time to deal with other matters.

Using Else-If Statements in Excel VBA

Else-If statements allow the developer to have their function or subroutine consider multiple alternatives. This can allow a piece of code to evaluate multiple criteria quickly. This will explain how to use Else-If statements in Excel VBA.

Ad

In this example, we are going to make a function that checks the score that student earned on a English proficiency exam and then assigns a string indicating what level the student is at. Below is a picture of the Excel worksheet before we create the function.

We want to fill the “Level” column automatically. Below is a partial visual of what the code will do.

We want Excel VBA to check the score and assigned a level based on the score. For example, if the student score 9 or higher than Excel VBA will assign a level of “Expert” to the student. If the students score 8 or higher but less than 9 than the student will be assigned the level of “Very good.” This continues until the score of 1 which is not seen in the graphic above.

The code below is the actual code that is placed in the VBA developer.

Function level(score As Double) As String
If score >= 9 Then
    level = "Expert"
ElseIf score >= 8 Then
   level = "Very good"
ElseIf score >= 7 Then
    level = "Good"
ElseIf score >= 6 Then
    level = "Competent"
ElseIf score >= 5 Then
    level = "Modest"
ElseIf score >= 4 Then
    level = "Limited"
ElseIf score >= 3 Then
    level = "Extremely limited"
ElseIf score >= 2 Then
    level = "Intermittent"
ElseIf score >= 1 Then
    level = "Nonuser"
End If
End Function

At the top of the code, we declare a function and give it the name “level”. This function takes one argument called “score” the input into the function is a numerical value but the output is a string. After this, we have are first ElseIf statement where VBA checks if the score is 9 or higher. If the score is then the level is set to expert. This process continues until the number 1. After this the If statement ends and the function ends.

Below is the output of the code found above

It appears everything is working.

Conclusion

This example shared one way to employ else-if statements in Excel VBA. With a basic example such as this it is possible to employ else-if statements in ways that are much more complex.

Errors & Subroutines in Excel VBA

Whenever you create a line of code you have to be aware of the potential of errors frustrating the end user of your product. This post will provide some guidance on how to deal with errors when developing subroutines for Excel VBA.

The Product

Our subroutine is a currency convertor. It specifically converts Thai Baht to US Dollars. Below is the code.

Here is what this code does.

  1. Line 1 declares sub along with its name
  2. Line 2 Declare variable we will need
  3. Line 3 will cause a box to appear that will ask the user to input the amount of Baht to convert
  4. Line 4 indicates the formula for conversion and the output

It is possible to run this code for the developer. However, this is not for a developer but for a user who may not be familiar with VBA coding. Therefore, we need to have a way to run this subroutine from the Excel spreadsheet.

To run this subroutine from the Worksheet we will create a button. This can be done by clicking

developers-> Insert->Button

Once the button is create Excel will ask you which macro to assign to it. Simply click on the macro that has the same name as the subroutine as shown below.

Implementation

If the user inputs numbers and presses okay the subroutine works fine as you can see below.

Here is the answer below

The Problem

However there are problems if we enter text into our input box or if we click cancel. In either case. We get the following.

Excel takes us to the VBA developer and shows an error message. This can be a serious problem if we want other people to use this subroutine. In order to fix this we will add a few lines to our code as shown below.

Here are the additions

  1. Line 3 as some code that says “On Error GoTo Here” this tells VBA that when there is any error to jump down to line 7 where the word “Here:” is
  2. Line 8 is executed whenever there is an error and this brings up the box “There was an error”
  3. Line 6 makes sure that the error box only occurs when there is an error. If you do not put this Exit Sub code in there the error box will appear every time you run the code whether there is an error or not.

Below is what happens now when there is an error.

Now when there is a problem this is what the end user will see. It’s not clear what the error is but this is less confusing then allowing them to see code and the developer application.

Conclusion

This post provided an example of how to deal with errors when working wit VBA. There is naturally more than one way to handle the problems presented here. However, this is one viable way.

Making If-Then Statements in Excel VBA

If-then statements are used in programming to allow a computer to execute an action based on a criterion. When this is done well, a program can do almost anything the developer wants. This post will provide an example of how to use if-then statements in Excel VBA.

Our goal is to create a subroutine in Excel VBA that determines if a number is divisible by five. In order to do this we have to do the following

  1. Create a variable to store input from the user
  2. Ask the user for a number
  3. Test if this number is divisible by 5
  4. If the answer is yes do one thing
  5. If the answer is no do something else
  6. exit the subroutine.

Below is a visual of what is described above

The Code

Below is the code for completing this task. There is no other way but to share the whole thing and then go through screenshots of each step.

Below is an explanation

The subroutine is called “divideByFive.” After this, we create a variable called x as an integer.

After creating the x variable, Excel will ask the user for a number in the input box as shown below. For this example, we inputted the number 25.

Once you input a number and press Enter and Excel will use the mod function to determine if the number is divisible by five. If the mod is zero this means there is no remainder and this triggers true for the if-then statement. Since our number is divisible by five, you will see the following which is the first message box.

If you put any number that is not divisible by 5 you will see the following, which is the second message box.

For simplicity, we skipped many steps, for example, if you type in text or press the cancel button you will get an error message.

Conclusion

If then statements can be used in your programming to achieve specific actions in your code. The example provided here is one simple way of doing this in Excel VBA

Making Subroutines in Excel VIDEO

Subroutines are another tool that can be developed in VBA. They are similar to functions but generally serve a different purpose. In particular, subroutines allow you to program in a modular manner in which different pieces of code are developed separately. In the video found here is an introduction to Creating a subroutine in Excel.

Creating a Subroutine in Excel VBA

Subroutine are another tool that can be used in Excel VBA for achieving the goals of the creator. Subroutine come from the idea of modular programming in which code that is reused multiple times is created and store in its own separate space and called whenever it is needed. By creating a subroutine separately it does not have to b recreated every time the functions it does are needed.

Many wonder what the difference is between a subroutine and a function. For generally readers this is actually highly esoteric but the main difference is that subroutines do not return a value while functions do. In addition, functions can be used in formulas but subroutines cannot. Right now this difference between functions and subroutines is not important but when programming becomes more complex this difference can be significant.

In the subroutine in this post we are going to make subroutine that calculates the area of a triangle. IN order to achieve this we need the subroutine to do following.

  1. Ask for the length of the triangle
  2. Ask for the width of the triangle
  3. Calculate the area
  4. Return the answer to the user

The code for this is not as complicated as it seems below is the code.

  1. In the first line we declare a subroutine use the Sub followed by the name of the subroutine.
  2. Line 2-3 is where we declare the two variables we will need. Input boxes appear to get this information
  3. Line 4 we calculate the area
  4. Line 5 we print the results of area in a message box

To run this subroutine you can press F5 while in the VBA developer. Once this is done you will see the following

First, Excel asks for the length of your triangle. BElow you can see I typed the number 10.

Next, Excel will ask you for the width of your triangle. I put 4

Finally, we get an answer of 20 which is the area of a triangle in this situation.

Conclusion

With a few lines of code we are able to have Excel calculate the area of a triangle. This could have been done with a function or directly on the worksheet. However, if there is a reason you do not want the user to interact with the worksheet or you need to repeat this calculation over and over a subroutine may be more appropriate.

Creating Functions in Microsoft Excel

Many people will use Excel for years and never be familiar with some of the more advanced features. For example, there are ways to develop your own functions and even programs inside Excel using Visual Basic Application (VBA). This powerful tool is sitting there waiting to make life easier for Excel users. This post will explain how to create your own functions using Visual Basic Application in Microsoft Excel.

Load the Developers Tab

First, you need to add the developer’s tab to your ribbon. To do this, do the following

  1. Click on File->Options->Customize ribbon
  2. Then click “customize main ribbon” and click on the developers checkbox as shown below

Setup for the Function

Now that the developer’s tab is available. We need to click on it and then click on visual basic, as shown below.

Once you click on “Visual Basic,” you will see the following

To make a function, we need to add a module. This is done by clicking

  • Insert->Module

You will see the following

The Function

We are going to make a simple function that calculates the area of a triangle. The code is only three lines and is shown below.

Function area(base As Double, height As Double) As Double
area = (base * height) / 2
End Function

Line one is declaring the function and giving it the name “area.” Inside the parentheses, we have two parameters, “base” and “height.” Each of these parameters is a data type called double in VBA, which can be used to store decimals. The function itself is also a double data type as this is outside the parentheses.

Line two shows the actual formula for the area of a triangle.

Lastly, we finish the function by adding “End Function.” Generally, VBA does this for you automatically.

Test the Function

Now we can see if the function works by going to Excel. You don’t have to save the function or anything like that in this example. Go to excel and call the formula, place two numbers inside the parentheses, separated by a comma, and press enter. Below is an example.

Below is the output after press enter

Success

Conclusion

This was a simple example of how to make a function in Excel using VBA. There is so much more to explore and learn, but this is a great way to get started.