Visual Basic Tutorial
Visual Basic Tutorial
Visual Basic Tutorial
edu
EXCEL Visual Basic Tutorial Problems (Version January, 2011) Dr. Prabhakar Clement Arthur H. Feagin Distinguished Chair Professor Department of Civil Engineering, Auburn University Home page: http://www.eng.auburn.edu/users/clemept/ Email: clement@auburn.edu
How to activate the Developer Tab? When you open EXCEL (in Office 2007) you should see a tab called Developer in the very end next to the View tab. If you dont then you need to activate it. You can do this by clicking on the office menu button (round button in left, where you have the print, save commands). At the very bottom of this menu you will see Excel options (see the figure below), click on that and then select (check mark) Show Developer tab in the ribbon. Say ok. Now you should see the Developer tab.
Note: Textbooks often follow different approaches for writing a VB code. The method shown here is a relatively simple and straight forward approach to write a VB code in EXCEL. The problem below shows how to create a VB button and rename it to name you like. But you dont have to rename, you can just leave it as the default name of Sub CommandButton1_Click() the program should still work. Test Problem-0: Develop a simple calculator that will add or subtract numbers two numbers entered in a spreadsheet. The final result will look like this:
The VB code for the ADD and SUBTRACT buttons are: Option Explicit Option Base 1 Private Sub codeAdd_Click() Dim a As Single, b As Single, c As Single a = Cells(1, 2) b = Cells(3, 2) c=a+b Cells(5, 2) = c End Sub Private Sub codeSubtract_Click() Dim a As Single, b As Single, c As Single a = Cells(1, 2)
We will use EXCEL cells to input the values and return the values right back to one of the cells. The command Cells(row,col) allows us to access cell values. Here we placed the command buttons ADD and SUBTRACT directly on the spreadsheet. This can be done by clicking on the Insert option under the Developer tab (if you dont see the developer tab, then go to the lab page of exercise which shows how to activate this tab) and then click on the command button option under ActiveX Control. Later click within the spreadsheet to create the button. Right click on the button and select Properties (or directly click on Properties next to the Design Mode button on top of EXCEL ribbon) and set the properties name to codeAdd and caption to ADD. Double click on the newly created command button and input the subroutine given above. Note, when you double clicked-- the system automatically created a subroutine codeAdd_Click(). The name codeAdd is the name of the button you defined under the properties menu. Repeat the steps for the subtract button. Once you are done, click on the Design Mode under Developer tab, this will allow you to switch to the RUN CODE mode. Now if you click on any of the command button your code will execute. If you want to modify the code then click again on the Design Mode, which will allow you to toggle between the design and run modes.
Test Problem-1: Problem Statement: Design a VB program to compute the areas of a rectangle. Input the dimensions of length and width of the rectangle from a spreadsheet as shown below:
Area Calculator Length (m) Width (m) Area (m^2) 2.210 4.444
Use EXCEL to create the above spreadsheet. If the decimal numbers are not displayed you can control the format by selecting the B2 to B4 cells and then choose Format, cells and you then select the display formats for three decimal places. This can be done by clicking on the Insert option under the Developer tab and then click on the command button option under ActiveX Control. Right click on the button and set the properties name to Mycode and caption to RUN MY CODE. Double click on the code and enter the following visual basic code: Option Explicit Option Base 1 Private Sub Mycode_Click() Dim Length As Single, Width As Single, Area As Single Length = Cells(2, 2) Width = Cells(3, 2) Area = Length * Width Cells(4, 2) = Area End Sub
Congratulations! You have successfully run your first visual basic program. Now let us look into the program and learn exactly what happened! Option Explicit. In this class, you should use this standard text in all your programs. If your program does not have this statement you will loose points, even if your code runs! This indicates that all the variables in your program will be defined by the programmer. This is an important statement and you should include this in all your codes. You have this all the time. You can force EXCEL to insert this automatically, by entering the VBE menu selection Tools, options, editor tab and check Require Variable Declaration. Option Base 1. This allows you to start matrices or arrays from Row-1 as opposed to Row-zero. You should use this option in all your program Private Sub Mycode_Click() (This is a standard line to indicate a sub routine that should be run when you click the button named Mycode) Dim Length As Single, Width As Single, Area As Single Here you are creating three variables with names Length, Width and Area that can store any real number with single precision. This holds signed IEEE 32-bit (4-byte) single-precision floating-point numbers ranging in value from -3.4028235E+38 through -1.401298E-45 for negative values and from 1.401298E-45 through 3.4028235E+38 for positive values. Singleprecision numbers store an approximation of a real number. Note: Another option to store real numbers in the variable Area is to use Area as Double. This will allow you to hold signed IEEE 64-bit (8-byte) double-precision floating-point numbers ranging in value from -1.79769313486231570E+308 through -4.94065645841246544E-324 for negative values and from 4.94065645841246544E-324 through 1.79769313486231570E+308 for positive values. Double-precision numbers store an higher level of approximation of a real number. Length = Cells(2, 2) Width = Cells(3, 2) Here you transfer (or assign) the values you entered in your EXCEL spreadsheet cells (2,2) and (3,2) to the program variables Length and Width. In this operation the input data is following from the spreadsheet to the VB program. Note: Some times it is easy to view your spreadsheet in RICI reference style when you use cells command to transfer data back and forth with the spreadsheet. To set RICI format, do the following: To turn R1C1 (means row-1 and column-1) reference style on or off 1. Click Options on the Tools menu, and then click the General tab. 2. Under Settings, select or clear the R1C1 reference style check box. You can go back to the standard format by removing the check mark in this box.
Set up a command button and enter the following code: Option Explicit Option Base 1 Private Sub Mycode_Click() Dim Length As Single, Width As Single, Area As Single Length = Cells(2, 2) Width = Cells(3, 2) Area = Length * Width Cells(4, 2) = Area If Length = Width Then Cells(5, 2) = "Square" Else Cells(5, 2) = "Rectangle" End If End Sub Exit the design mode and run the code. You will see that your spreadsheet will be updated with the data shown below:
Area Calculator-Ver2 Length (m) Width (m) Area (m^2) Object Type 2.100 4.000 8.400 Rectangle
Also,
Area Calculator-Ver2 Length (m) Width (m) Area (m^2) Object Type 2.100 2.100 4.410 Square
This program is almost identical to the previous program, except you used if-then-endif structure to make a decision on the type of object you are dealing with it. Note: It is always important to use proper indentation when you use IF and For-next conditions. It is easy to use Tab for this purpose. However, the default for tab is 4 spaces, but you can change this to two spaces by using Tools, options, Editor tab and change Tab Width to 2.
Test Problem-3: Understanding simple For-Next Loop Problem Statement: Design a VB program to compute the areas of n number of squares and circles, given their characteristic dimensions (length of the side for squares or radius for circles). The value of n and the dimensions are entered in the spreadsheet as show below: Number of squares/circles 6 Dimension Square_area Circle_area 1 2 3 4 5 6 Use EXCEL to create the above spreadsheet. Setup a command button and enter the following code: Option Explicit Option Base 1 Private Sub Mycode_Click() Dim i As Integer, n As Integer Dim A As Single, result1 As Single, result2 As Single n = Cells(2, 1) For i = 1 To n Step 1 A = Cells(3 + i, 1) result1 = A ^ 2 result2 = 3.14 * A ^ 2 Cells(3 + i, 2) = result1 Cells(3 + i, 3) = result2 Next i End Sub Run the code and you will see that your spreadsheet will be updated with the data shown below: Number of squares/circles 6 Dimension Square_area Circle_area 1 1 3.14 2 4 12.56 3 9 28.26 4 16 50.24 5 25 78.5 6 36 113.04 Now let us look into the program and learn exactly what happened! Dim i As Integer, n As Integer
Option Explicit Option Base 1 Private Sub Mycode_Click() Dim grade(10) As String Dim Points(10) As Single Dim i As Integer, n As Integer n = 10 For i = 1 To n Step 1 Points(i) = Cells(1 + i, 1) Next i For i = 1 To n If Points(i) >= 90 Then grade(i) = "A" ElseIf Points(i) >= 80 Then grade(i) = "B" ElseIf Points(i) >= 70 Then grade(i) = "C" ElseIf Points(i) >= 60 Then grade(i) = "D" Else grade(i) = "F" End If Next i For i = 1 To n Cells(1 + i, 2) = grade(i) Next i End Sub Now run the code to see results.
Note: in order display dollar sign you need to select that column and set the format using format, cells currency. Set up a command button and enter the following code: Option Explicit Option Base 1 Private Sub Mycode_Click() Dim Sum As Single, Average As Single Dim i As Integer, n As Integer, Salary(7)as single n = Cells(1, 2) For i = 1 To n Salary(i) = Cells(2 + i, 2) Next i Sum = 0# For i = 1 To n Here we are Sum = Sum + Salary(i) initializing the Next i variable sum as zero Average = Sum / n Cells(n + 4, 2) = Average End Sub Run the code and you will see that your spreadsheet will be updated with the data shown below:
Number of staff Name John Jane Jacob Josh Jay Jack Joy Average 7 Salary $100,000.00 $150,000.00 $90,000.00 $25,000.00 $50,000.00 $75,000.00 $89,000.00 $82,714.29
Note in the above code we have used the variable sum as an accumulator. Note when i=1, sum=0, then it is assigned a value of sum+100,000, which is 100,000. When i=2 sum = 100,000 and then it is assigned a value of 100,000+150,000.. this operation is repeated until all salaries of all the employees are added.
10
11
12
13
14
Note, between matrix A and B we leave a blank column, also between Matrix B and C we leave a blank column. Set up a command button and enter the following code: Option Explicit Option Base 1 Private Sub Mycode_Click() Dim i As Integer, j As Integer, n As Integer Dim A() As Single, B() As Single, C() As Single n = Cells(1, 2) ReDim A(n, n) As Single, B(n) As Single, C(n) As Single 'Read Matrix A from spreadsheet For i = 1 To n For j = 1 To n A(i, j) = Cells(2 + i, j) Next j Next i 'Read Matrix B from spreadsheet For i = 1 To n B(i) = Cells(2 + i, n + 2) Next i 'Perform matrix multiplication to compute C For i = 1 To n C(i) = 0# For j = 1 To n C(i) = C(i) + A(i, j) * B(j) Next j Next i 'Output the results to spreadsheet For i = 1 To n Cells(2 + i, n + 4) = C(i) Next i End Sub
15
Now let us review the code block-by-block Dim A() As Single, B() As Single, C() As Single n = Cells(1, 2) ReDim A(n, n) As Single, B(n) As Single, C(n) As Single In the above three lines, we use a powerful dynamic array allocation option to define the sized of the array. The first line simply tells the code that A, B, and C are single precision arrays. However, it does not say anything about the size or shape (dimensionality) of the arrays. In the second line we read n from the spreadsheet. In the third line, we use the value of n to define the size and the number of dimensions (also know as shape) of the array.
Note, 2 is used to skip the 'Read Matrix A from spreadsheet For i = 1 To n first two rows For j = 1 To n A(i, j) = Cells(2 + i, j) Next j Next i In the above block we read the values of the elements in array A from the spreadsheet.
'Read Matrix B from spreadsheet For i = 1 To n B(i) = Cells(2 + i, n + 2) Next i In the above block we read the value B.
For i = 1 To n C(i) = 0# For j = 1 To n C(i) = C(i) + A(i, j) * B(j) Next j Next i Above code segment performs the matrix multiplication operation, which identical to what we did when we performed hand calculations. For i = 1 To n Cells(2 + i, n + 4) = C(i) Next i Above code segment outputs the data back to the spreadsheet.
16
To learn more about VB, visit this nice website: http://www.engineering.usu.edu/cee/faculty/gurro/Software_Calculators/ExcelVBA/ExcelVBAE xamples.htm
Some useful information I got from this site are: 1) To get numerical data from the worksheet into your VBA code use functions Range or Cells. For example, to get the value of cell "B2" into variable a in your VBA code use: a = Range("B2").Value or Alternatively, you could use, a = Cells(2,2).Value to load your data value. To place data from your VBA code to the worksheet use the same functions Range and Cells, e.g., Range("C2").Value = r1 or Cells(3,2).Value = r1 To place string data from your VBA code to the worksheet use, for example: Range("M2") = "Int. = " or Cells(15,2) = "Int. = " Notice that function Range takes as argument a string referring to the cell of interest, e.g., Range("F15"), while the function Cells takes two arguments, namely, the indices for the row and column of the cell of interest, e.g., Cells(25,31). To clear a value in cell D8, use the commands Range("D8").Select Selection.ClearContents To clear a rectangular region of cells Range("D10:F12").Select Selection.ClearContents Excel provides a number of functions that are not available in Visual Basic, e.g., ACOS, ASIN, BESSELI, etc. You can use the cells in the worksheet to evaluate formulas that use these functions and then bring those values into your VBA code. To see a list of the functions available in Excel, click on a cell in a worksheet, place and equal sign in it and then click on the button labeled fx in the Excel toolbar. A listing of the functions by categories will be provided. The categories include All, Date & Time, Math & Trig, Statistical, etc. Click on any category to get a listing of functions available. [Functions list window] There is a category of functions referred to as Engineering functions that include advanced engineering mathematical functions, e.g., Bessel functions, complex number conversion, error function, etc. If that category is not available in your Excel functions, use the option Tools>Add Ins... and mark the boxes Analysis Toolpack and Analysis Toolpack - VBA to add the engineering functions. Press OK to load the functions.
17