19
1 VBA Macros in ChEn 1703 Welcome to programming macros with visual basic for applications (VBA) in MS Excel. You will hear this referred to as either macros or VBA. The best way to learn this is by doing so I have set up a series of examples that I hope you will find helpful. I have tried in a series of notes to explain nearly everything that is really important for scientific computing. No summary like this will ever be complete so I hope you will share what you learn with the class so that we can learn from you too. Often in your career you will be faced with situations in which you do not seem to have every tool you need and that may be that case with learning how to program. Sometimes that is because you do not see that you really do have the tool. Having friends and colleagues who you can talk with is very helpful and that is especially true in programming. Sometimes you really do not have what you need and that is when you have to take the initiative and research things for yourself. At the heart of any programs are the symbols we use to represent numbers and in some cases letters. These are variables just like those we use in algebra and calculus. The computer needs to know which types of variable you are using so that it can allocate the right amount of memory in the right places. Just like you know whether a word is a noun or a verb from context, VBA thinks is knows what a variable is based on the number that you assign to it. The table below summarizes what variables look like and examples of where we will use them. There are many other data types available in VBA, but this set encompasses the most useful ones. Variable Type Examples Usage Integers 5,-2,0 Loops Reals—Single precision (8 digits) —Double precision (16 digits) 2.1, 42, 3.141592654, 5# Numbers in calculations Strings “Hi Mom”, u012345 Location of cells Boolean True, 1, False, 0 Loops, If’s In the remainder of this document, we will introduce the principles of macro programming through several examples. The examples are often simple to emphasize how use the programming techniques. At the end of this document, we will develop some more advanced examples to demonstrate their utility for scientific programming. I would recommend that you copy these macros into excel to see how they work. Pay particular attention to where you need to give the program input. Programming does not come all at once but patience and persistence do pay off and students who do so will find themselves successful at the end. In addition to describing input/output protocols for VBA to and from Excel, we will describe three types of algorithms, in which you should become proficient in. The first type of algorithm is sequential where every step proceeds one immediately after another. The second type of algorithm is iterative where the step by step algorithmic process has internal loops. The third type of algorithm is conditional where the algorithm must make decisions between options. Twelve examples highlighting each of these features are given below. The first example is of a simple absolute value computation.

Summary of VBA for Scientific Computing 9-25-2013 v1

Embed Size (px)

DESCRIPTION

VBA

Citation preview

Page 1: Summary of VBA for Scientific Computing 9-25-2013 v1

1

VBA Macros in ChEn 1703 Welcome to programming macros with visual basic for applications (VBA) in MS Excel. You will hear this referred to as either macros or VBA. The best way to learn this is by doing so I have set up a series of examples that I hope you will find helpful. I have tried in a series of notes to explain nearly everything that is really important for scientific computing. No summary like this will ever be complete so I hope you will share what you learn with the class so that we can learn from you too. Often in your career you will be faced with situations in which you do not seem to have every tool you need and that may be that case with learning how to program. Sometimes that is because you do not see that you really do have the tool. Having friends and colleagues who you can talk with is very helpful and that is especially true in programming. Sometimes you really do not have what you need and that is when you have to take the initiative and research things for yourself. At the heart of any programs are the symbols we use to represent numbers and in some cases letters. These are variables just like those we use in algebra and calculus. The computer needs to know which types of variable you are using so that it can allocate the right amount of memory in the right places. Just like you know whether a word is a noun or a verb from context, VBA thinks is knows what a variable is based on the number that you assign to it. The table below summarizes what variables look like and examples of where we will use them. There are many other data types available in VBA, but this set encompasses the most useful ones. Variable Type Examples Usage Integers 5,-2,0 Loops Reals—Single precision (8 digits) —Double precision (16 digits)

2.1, 42, 3.141592654, 5#

Numbers in calculations

Strings “Hi Mom”, u012345 Location of cells Boolean True, 1, False, 0 Loops, If’s

In the remainder of this document, we will introduce the principles of macro programming through several examples. The examples are often simple to emphasize how use the programming techniques. At the end of this document, we will develop some more advanced examples to demonstrate their utility for scientific programming. I would recommend that you copy these macros into excel to see how they work. Pay particular attention to where you need to give the program input. Programming does not come all at once but patience and persistence do pay off and students who do so will find themselves successful at the end. In addition to describing input/output protocols for VBA to and from Excel, we will describe three types of algorithms, in which you should become proficient in. The first type of algorithm is sequential where every step proceeds one immediately after another. The second type of algorithm is iterative where the step by step algorithmic process has internal loops. The third type of algorithm is conditional where the algorithm must make decisions between options. Twelve examples highlighting each of these features are given below. The first example is of a simple absolute value computation.

Page 2: Summary of VBA for Scientific Computing 9-25-2013 v1

2

Example 1 Sub Absolute_Value_If() ‘This macro takes the absolute value of the value in A1 and places it in B1 Dim x As Single Range("A1").Select x = ActiveCell.Value If x < 0 Then x = -x End If Range("B1").Select ActiveCell.Value = x End Sub Notes: 1. Macros have the following form: Sub NameString() ~ ~ End Sub Variables names you should replace with your own, like NameString, will be italicized.

Your program will go where you find the ~ ~. Sub stands for subroutine. 2. There is another form that you can use called Function with a similar form: Function NameString() ~ ~ End Sub The difference between the Sub and Function formats has to do with the way that variables

are passed (i.e. transferred in and out of the subroutine or function). If you place a function or subroutine within a subroutine, you can give variables to the inner or nested function or subroutine by placing them within the parentheses following NameString. A subroutine will return several values, while a function will only return one value. In practice you could write either a function or a subroutine to calculate the absolute value so the distinction is of little value to us most of the time; when in doubt use a subroutine because it is more versatile. Additionally functions can be used both as spreadsheet functions and called from within a subroutine, where as subroutines have to be played as macros or called from within subroutines (see the call statement in ch 5 of your text for more information on calling subroutines).

3. To activate a particular cell in a spreadsheet use the Range nomenclature as in Range(LocationString).Select. The LocationString will be a letter representing the column followed by a number that

corresponds to a row. For exampled, Range(“A1”).Select will place the cursor on cell A1 at

Start

End

Input x from “A1”

x<0

Output x to “B1”

no

yes

x=-x

Page 3: Summary of VBA for Scientific Computing 9-25-2013 v1

3

the upper left hand corner of the spreadsheet. Similarly, Range(“C25”) will place the cursor in the 25th row of the C column of the active spreadsheet. This is called absolute referencing. There is a relative referencing scheme that you can use. It is mildly more cumbersome so we will not emphasize it in this class. When you record your macros (particularly in Excel 2007 you should make sure that your referencing system is set to absolute).

4. You know how to add numbers by simply using the plus sign. To add strings you use the “&” symbol. For example

if String1 = “A” and String2 =”B” then String1 & String2 =“AB”. Similarly, if String1 = “to” and String2 =”get” and String3 =”her” then String1 & String2 & String3 =“together”. Mostly, we will want to add strings so that we can find locations. A common strategy is to

choose a column but allow the row to change by assigning the variable j to be a positive integer (not zero!) and writing

Range(“A” & j).Select. This line places the cursor in the jth row of the A column. 5. Once you have selected a position on the spreadsheet you will need to assign its contents to a

variable. If x is the name of the variable then you can choose either x=activecell.value for numbers including integers and reals or x=activecell.text for strings. There are other options but they are not as frequently used in scientific

computing. To place a variable in a cell you just turn these assignment statements around. For example after determining the value of x in the program you can write

activecell.value=x to place the number stored in x in the active cell of the spreadsheet or numbers including

integers and reals or activecell.text=x. for text. If you use activecell.text the spreadsheet will treat it as a letter instead of a number.

Beginning students often get confused here and then cannot use the results of the calculations in their spreadsheets or find that the indentation looks different from the numbers they put in by hand.

6. Conditionals are very important within your programs. There are three ways to write a conditional

(a) If SomeTrueExpression Then WhatHappensWhenTrue (b) If SomeTrueExpression Then WhatHappensWhenTrue End If (c) If SomeTrueExpression Then WhatHappensWhenTrue Else WhatHappensWhenFalse End If Form (b) is more commonly used than (a).

Page 4: Summary of VBA for Scientific Computing 9-25-2013 v1

4

Condition True?

no

yes

What to do if yes

Condition True?

no

yes

What to do if yes

What to do if no

(a) and (b) (c) 7. Assignment statements are where you do the actual calculations. For example, x=x+1. This expression is best read as “x is set equal to x + 1”. This means that the program adds 1

to the previous value of x and assigns that as the new value of x. You can use most of the expressions that would be available in the spreadsheet. For example, you can take the third root of x by writing

x=x^(1/3). Be aware that some of the functions you use in workbooks are limited to only the workbook.

In that case pick a place on the spreadsheet you know you will never use like DD62543 and use that place to calculate the function.

8. Comments can be included by inserting ‘ in front of any writing. Comments are very important and should be included.

9. You should always dimension your variables. Your programs can run without dimensioning but this is a very good programming habit because it will help you quickly find errors (if any). To declare a variable as a particular type of variable, we use the Dim command. The Dim command should go immediately under the Sub line and any comments but before you use any variables. Some examples include:

Dim NumberOfIntervals As Integer Dim xLowerLimit As Real Dim Atotal As Double Dim GradeString As String Dim LoopFlag As Boolean

Sometimes you need to choose among more than two cases where only a simple statement that will either answer the question of yes/no or true/false remains insufficient. Then you have two options. Either you can use nested if-then statements or you can use a case statement. Let’s first look at the nested if structure in an example. Here we use the if-else construction multiple times. Example 2 Sub Grade_Calcs_Nested_If() 'This macro takes the final percentage in A1 and returns a letter grade in B1 Dim p As Single Dim GradeString As String

Page 5: Summary of VBA for Scientific Computing 9-25-2013 v1

5

Range("A1").Select p = ActiveCell.Value GradeString = "" If p >= 90 Then GradeString = "A" Else If p >= 80 Then GradeString = "B" Else If p >= 72 Then GradeString = "C" Else If p >= 64.9 Then GradeString = "D" Else GradeString = "F" End If End If End If End If Range("B1").Select ActiveCell.Value = GradeString End Sub

Start

End

Input p from “A1”and set Grade =“”

p≥90

Output Grade to “B1”

no

yes

Grade = A

p≥80 no

yes

p≥72 no

yes

no

yes

p≥64.9

Grade = B Grade = C Grade = D Grade = F

Notes: 1. Note that when we use a nested structure that we indent the contents. This makes the

program look something like a nest if you turn the paper on its side. This is a really good

Page 6: Summary of VBA for Scientific Computing 9-25-2013 v1

6

habit to get into. Sometimes you will have hundreds to thousands of lines of code within each part of the if-then statement and indenting will be critical to keeping track of what is happening.

2. In excel programs greater than, less than, and equal to behave much as one might expect. You can combine them to write the equivalent of “less than or equal to” as <=. Others follow similarly. For not equal two, we write “<>”, which is a combination of the less than and greater than symbols.

The alternative to the nested “if” structure is the case statement. Here you input a value

and then give it instructions based on its value. To show you how this is to be done, we first rewrite the absolute value and grading programs. Example 3 Sub Absolute_Value_Case() 'This macro takes the absolute value of the value in A1 and places it in B1 Dim x as Single Range("A1").Select x = ActiveCell.Value Select Case x Case Is < 0 x = -1 * x Case Is >= 0 x = x End Select Range("B1").Select ActiveCell.Value = x End Sub Example 4 Sub Grade_Calcs_Case() 'This macro takes the final percentage in A1 and returns a letter grade in B1 Dim p As Single Dim GradeString As String Range("A1").Select p = ActiveCell.Value GradeString = "" Select Case p Case Is >= 90

Page 7: Summary of VBA for Scientific Computing 9-25-2013 v1

7

GradeString = "A" Case 80 To 90 GradeString = "B" Case 72 To 80 GradeString = "C" Case 64.9 To 72 GradeString = "D" Case Is < 64.9 GradeString = "F" End Select Range("B1").Select ActiveCell.Value = GradeString End Sub Notes: 1. Case allows you to select from a series of values. The case construct has the following form Select Case VariableToBeEvaluated Case RangeOfValuesWithinWhichTheVariableToBeEvaluatedMayFit WhatYouDoIfConditionalIsTrue ‘Include additional cases as necessary End Select 2. There are three types of case construction. (a) If your VariableToBeEvaluated will match an individual value. For example, Case 94 Note however that 94.1 and 93.9 are not included in this case (b) If your VariableToBeEvaluated will fall within a bounded range, then you specify the

boundaries of the range. For example, Case 80 To 90 This is equivalent to 80 ≤ x <90, so 90.0000 would not fall in this range but 80.0000 would. (c) If your VariableToBeEvaluated will fall within an unbounded range or includes infinity,

then you specify the one known boundary with an inequality in the following form Case Is >= 94

3. Please notice how much more elegant the case structure is for longer sets of conditions. Both nested ifs and cases do the same job, but one will look nicer than the other. For small structures (say for less than 3 conditions) the if-then-else construction is better. For longer lists of conditions the case is probably better. For example, imagine how long the program could get by including the pluses and minuses in the grading system. The nested if’s would quickly become unwieldy whereas the case would be much nicer. The computer does the same thing in both options but the user interface is different.

4. The flow diagrams with cases for examples 3 and 4 are the same as those with ifs for examples 1 and 2.

Page 8: Summary of VBA for Scientific Computing 9-25-2013 v1

8

These programs are great if you only have one cell to evaluate. However, the real power of programming comes when you can get a computer to repeat what would otherwise be tedious calculations. It is quite clear that you could take the absolute value in your head or rather easily determine your letter grade from a table. But determining the letter grades for 100 students is a different story. At 20 seconds per person that would take 2000 seconds, which is just over 33 minutes. Now do that several times per semester over several semesters for several classes and the time can really add up. Calculating one absolute value takes no time at all but doing similarly simple calculations for 1000 values can really add up. Here we need a computer to do the same thing over and over again. Loops provide that functionality. There are two types of loops. The first is called a for loop or for-next loop. Choose this form when you know exactly how many times you want to repeat a function. For example, if you know that you want to calculate the absolute values of 100 values in a single column from row 2 to row 101. To show how to use the for-next construction we will write a macro to count from 5 to 500 in steps of 5. Example 5 Sub Steps_Of_Five_For() 'This macro counts from 5 to 500 in steps of 5 and places these values in column A Dim i As Integer For i = 1 To 100 Range("A" & i + 1).Select ActiveCell.Value = 5 * i Next 'i End Sub

Start

End

For i = 1-100

Output 5*i

Start

i=1

i<=100

?

Y

N

End

Output 5*i

i=1

Next ‘i

Notes: 1. For-next loops have the following form: For Index = StartingInteger To EndingInteger ~ ~ Next ‘Index We customarily indent the contents of a loop much like we did with if-then statements.

Page 9: Summary of VBA for Scientific Computing 9-25-2013 v1

9

2. The index must be an integer! Real numbers or strings will not work. This is a common mistake that beginning programmers make. For example, a very nice problem asks you to write the values from 0.5 to 9.5 in steps of 1. Many beginning programmers will write

For i = 0.5 to 9.5. This will cause an error. Use integerial indexes and then multiply the index by a fraction later in the program.

3. You do not necessarily have to step through loops in ever increasing steps of +1. You can choose other integerial steps for example. For-next loops have the following form:

For Index = StartingInteger To EndingInteger Step Interval ~ ~ Next ‘Index Here the interval may be any integer greater than 1 and it may be either positive or negative.

For example to count down by two’s you may select a step of -2. Again, we customarily indent the contents of a loop much like we did with if-then statements.

4. When I create nested loops, I might have several next statements in a row. It is a good habit to write the index used after the next so that you do not get lost. It is good form and prevents sloppiness.

Another looping example is that of calculating lots of grades. Say this time that the final percentages are in column C from row 2 to 33. Then the following macro will calculate the grades for all 32 students in the class. Example 6 Sub Grades_For32_Students_For() 'This macro determines the grades for a fixed number of students, here 32 'It takes percentages from column C and places them in column D. Dim i As Integer Dim p As Single Dim GradeString As String For i = 1 To 32 Range("C" & i + 1).Select p = ActiveCell.Value GradeString = "" 'setting the GradeString to blank is particularly important because all grades must be earned Select Case p Case Is >= 90 GradeString = "A" Case 80 To 90 GradeString = "B" Case 72 To 80 GradeString = "C" Case 64.9 To 72

Page 10: Summary of VBA for Scientific Computing 9-25-2013 v1

10

GradeString = "D" Case Is < 64.9 GradeString = "F" End Select Range("D" & i + 1).Select ActiveCell.Value = GradeString Next 'i End Sub Notes: 1. To prevent the macro from using the same input and output cells 32 times, we have to adjust

the input to the Range function. This is done by linking the index to the row number. We have to add one to the index to determine the row. The remainder of the macro just combines the two earlier macros together. The case is “nested” within the loop.

2. In loops you must be careful to reset the starting values to zero or blanks otherwise variables will carry over from the previous iteration of the loop. Every time one cycle of the loop is executed, it is called an “iteration”.

Start

End

Input p from “C” & i and set Grade =“”

p≥90

Output Grade to “B1”

no

yes

Grade = A

p ≥ 80 no

yes

p ≥ 72 no

yes

no

yes

p≥64.9

Grade = B Grade = C Grade = D Grade = F

For i = 1-100

Next ‘i

So what do we do when we do not know the number of times to iterate? The for-next structure does not work so nicely then. In that case we can use the while loop or the while-wend loop. Example 7 provides an instance of this type of looping. This program is designed to figure out how many rows are used in a file so that subsequent loops can use the for-next structure. Example 7

Page 11: Summary of VBA for Scientific Computing 9-25-2013 v1

11

Sub Find_Blank_While() 'This macro finds the first blank and then reports the number of filled or nonblank rows Dim Counter As Integer 'the first section of this macro sets up the initial values Counter = 2 'we set counter equal to 2 because it is our first row number Range("A" & Counter).Select While ActiveCell.Text <> "" Counter = Counter + 1 Range("A" & Counter).Select Wend Range("A1").Select ActiveCell.Value = Counter - 1 End Sub

Start

End

While Cell not blank

Raise Counter Move to

A&Counter

Counter = 2 Move to A2

Output Counter-1 to

“A1”

Start

Cell Blank

?

Y

N

Wend

Counter = 2 Move to A2

Raise Counter Move to

A&Counter

End

Output Counter-1 to

“A1”

Notes: 1. While loops have the following form: While SomethingIsTrue ~ ~ Wend ‘Index We customarily indent the contents of a loop much like we did with if-then statements.

Every while loop also needs a counter and a way to change the SomethingIsTrue into SomethingIsFalse. Without the latter you will have an infinite loop, meaning the loop will go on forever and the program will never stop.

Page 12: Summary of VBA for Scientific Computing 9-25-2013 v1

12

2. To get out of infinite loops you have one of three options: (1) press the escape—always a good first thing to do, (2) use control-alt-delete to bring up the task manager and shut down excel—there is an equivalent for Apple-Mac systems, or (3) turn off the power.

3. Counters are critical and must be included in each while loop as a matter of good form. They should increase in value usually by 1 each cycle or iteration. Usually they start at 1 but here they started at 2 because we wanted the Counter to reflect the last row number that had something in it.

3. Remember that "" stands for an empty string. Cells without anything in them are blank or empty.

This macro works and performs the proper functions. However, it can be improved in two ways. First, there is a real danger that you will get into an infinite loop. This is not a problem with for-next loops because you specify the number of times that they run, but while loops can loop forever if you make a mistake in the programming. This is the primary reason that many scientific programmers prefer to use for-next loops instead of while loops. To avoid this it is a good thing to put in an escape clause. This can be done by specifying the number of times that a loop can run. To make that happen, the second improvement is to use flags. Flags are Boolean variables. While loops work when the argument at the front is true. In the example immediately above the loop worked when (ActiveCell.Text ≠ ""). The first time that ActiveCell.Text = "", the program exits the loop and proceeds with the remaining instructions. We can replace (ActiveCell.Text ≠ "") with a looping flag. Here is the improved macro: Example 8 Sub Find_Blank_While_Version2() 'This macro finds the first blank and then reports the number of filled or nonblank rows Dim Counter As Integer Dim LoopFlag As Boolean 'the first section of this macro sets up the initial values Counter = 2 'we set counter equal to 2 because it is our first row number LoopFlag = True While LoopFlag Counter = Counter + 1 Range("A" & Counter).Select If ActiveCell.Text = "" Or Counter = 1000 Then 'or some really big number LoopFlag = False End If Wend 'LoopFlag Range("A1").Select ActiveCell.Value = Counter - 1 End Sub

Page 13: Summary of VBA for Scientific Computing 9-25-2013 v1

13

Start

LoopFlag

?

Y

N

Raise Counter Move to

A&Counter

End

Output Counter-1 to

“A1”

Counter = 2 LoopFlag=True

Cell Blank Or Counter

≥103

LoopFlagFalse

Y

N

Start

End

While LoopFlag

Raise Counter Move to

A&Counter

Output Counter-1 to

“A1”

Wend

N

Counter = 2 LoopFlag=True

Cell Blank Or Counter

≥103LoopFlag

False

Y

Notes: 1. This is not a program that you can write with a for-next loop. It requires a while loop. 2. You can of course nest while loops much like you can nest for-next loops. To prevent

confusion with nested loops, put the name of the looping flag immediately after the wend. Even if you only have one loop, it is good form to get into the habit now.

3. Note the use of the Or to combine true and false statements. The logical operators OR and AND work perfectly here. They behave just like they do on worksheets as discussed in class. In fact this is a very nice way to combine two otherwise identical if-then statements. The more cumbersome alternative is

If ActiveCell.Text = "" Then LoopFlag = False End If If Counter = 1000 Then 'or some really big number LoopFlag = False End If 4. There are other loop forms that you can choose from including the do loop. However, with

these two types of loops, you can perform every essential function that we will run into in scientific computing.

Here is another example of the while loop. I have often found myself scrolling through hundreds of numbers to find the maximum. This macro use a worksheet function to determine the maximum and then will report its row number. Example 9 Sub Find_Maximum_While() 'This macro finds the row number corresponding to the maximum starting from row 3

Page 14: Summary of VBA for Scientific Computing 9-25-2013 v1

14

'we can use work book function to first determine what the maximum is Dim LoopFlag As Boolean Dim Counter As Integer Range("A2").Select ActiveCell.FormulaR1C1 = "=MAX(R[1]C:R[65534]C)" Maximum = ActiveCell.Value Counter = 2 'we set counter equal to 2 because it is our first row number LoopFlag = True While LoopFlag Counter = Counter + 1 Range("A" & Counter).Select If ActiveCell.Value >= Maximum Or Counter = 1000 Then 'or some really big number LoopFlag = False End If Wend 'LoopFlag Range("A1").Select ActiveCell.Value = Counter End Sub Notes: 1. Here we have used a workbook function to find the maximum. You can use any workbook

function in this way. This function uses relative referencing instead of absolute referencing. Absolute referencing specifies the exact location of the cells, like “A1” or “C25”. Relative referencing gives the location of the cells relative to the current active cell. Absolute referencing is usually better because it is harder to give a reference that is not on the spreadsheet, which is unfortunately common even for experienced programmers. Relative referencing follows the form R[n]C[m], where n is the number of rows below and m is the number of rows to the right of the active cell. If you want to go up or to the left use negative values for n and m.

2. There are several other loops that are available in VBA. You can explore them if you wish, but these two loops will give you all of the basic tools you need to program scientifically.

Armed with these basics, we can write more advanced macros. This next macro uses nested for-next loops make a histogram plot of your quiz scores. In the first set of loops we calculate the overall quiz score, and in the second set of loops we calculate the scores for the reading. In the first set, the outer loop ranges from 0 to 10 because these were the possible quiz scores. The inner loop ranges scans across all the scores to count those that have the score specified in the first loop. Essentially, the program first looks for all of the scores that are between 0.000 and 0.999 and tallies the count. It then looks for scores that are between 1.000

Page 15: Summary of VBA for Scientific Computing 9-25-2013 v1

15

and 1.999 and counts them. It then looks for scores that are between 2.000 and 2.999 and tallies them up, and so forth. You could do this by hand but a computer is definitely faster. Example 10 Sub Histograms() 'The overall quiz scores are stored in column B and the scores for the reading question in C. 'the macro places (the lower limit of the) bin in column D and its value in E for the total quiz 'the macro places (the lower limit of the) bin in column F and its value in G for the reading Dim j As Integer Dim i As Integer Dim Counter As Integer Dim x As Single For j = 0 To 10 Count = 0 For i = 2 To 108 Range("B" & i).Select x = ActiveCell.Value If (x >= j And x < j + 1) Then Count = Count + 1 End If Next 'i Range("D" & j + 2).Select ActiveCell.Value = j Range("E" & j + 2).Select ActiveCell.Value = Count Next 'j For j = 0 To 2 Count = 0 For i = 2 To 108 Range("C" & i).Select x = ActiveCell.Value If (x >= j And x < j + 1) Then Count = Count + 1 End If Next 'i Range("F" & j + 2).Select ActiveCell.Value = j Range("G" & j + 2).Select ActiveCell.Value = Count Next 'j

Page 16: Summary of VBA for Scientific Computing 9-25-2013 v1

16

End Sub Notes: 1. Be sure to keep track of which loops you are in. This can be done by comments and by

indentation. 2. Also it is very important when programming to pay attention to the inequalities. For example

if we had written If (x >= j And x <= j + 1) Then Then we would have had a double counting problem. Each score except for 0 and 10 would

have been counted twice. Getting something wrong like this in class is one thing but on the job it can be very painful.

3. There is something that could really improve this macro. What do you think it is? Another example of a valuable scientific program is determining the value of an integral.

You may remember from calculus that there are many ways to numerically determine the value of an integral. These include the rectangle rule, the trapezoid rule, Simpson’s rule, etc. If you are interested in numerical methods to calculate each of these there are several courses available on campus, including Chemical Engineering 2450. Here we will choose the simplest of these techniques. Say for a moment that we want to calculate the integral of f(x)=1/(1+x2) from x= 0 to x=1. We know from calculus that the smaller the interval the more accurate the approximation so let’s choose 100 intervals within our range of x. The area of each small rectangle will be the product of the height from f(x) and the width of the interval x. When we are done, we will place the value in cell “F4” (for no particular reason at all). Example 11 Sub Calculate_Integral() Dim xLowerLimit As Single Dim xUpperLimit As Single Dim NumberofIntervals As Integer Dim Atotal As Single Dim IntervalWidth As Single Dim i As Integer Dim xn As Single Dim fxn As Single Dim DifferentialA As Single xLowerLimit = 0# 'This is a real number xUpperLimit = 2# 'This is a real number NumberofIntervals = 100 'Must be an integer Atotal = 0# IntervalWidth = (xUpperLimit - xLowerLimit) / NumberofIntervals For i = 1 To NumberofIntervals xn = IntervalWidth * i fxn = 1 / (1 + (xn ^ 2))

Page 17: Summary of VBA for Scientific Computing 9-25-2013 v1

17

DifferentialA = IntervalWidth * fxn Atotal = Atotal + DifferentialA Next 'i Range("F4").Select ActiveCell.Value = Atotal End Sub Notes: 1. The pound sign (#) denotes a decimal followed by all zeros. It is used to make sure that you

know that the number leading the # is not an integer. For example, 1 is an integer, whereas 1# is equivalent to 1.0000… You and I may just say that it is one, but a computer cares because integers are treated very differently from real numbers both in terms of how they are stored and how the computer does the math.

2. One of the skills that you will need to develop is that of an error checker. This has two parts. First you need to write your programs such that they can easily be checked for errors. Some students like to put entire calculations on a single line. We could have done that above, but if you need to check for errors, that makes it difficult. Breaking mathematics operations into multiple lines can really simplify your error checking.

3. If you want to know what your program is doing, run it in debug mode. The most helpful expression is key F8 at the top of your keyboard or using the “Step Into” command from the Debug menu. When you then run your program, the macro will step through each line of your code one by one with each application of this command. Use the mouse to scan over the variables and a box with each variable’s value will pop up. This way you can know what values the computer thinks it is using.

4. Another debugging hint is to place the cursor on a line that you want to evaluate. Then use the toggle break point command (key F9). When you start the program it will run to the toggle point and pause so that you can see what values the computer is using at the breakpoint. Again use the mouse to see the values.

5. Sometimes when writing a macro you run it, there is an error, you fix it, and then the program will not run. In this case be sure to press the stop button (a blue rectangular square). Errors only interrupt execution of the program so you often have to stop it yourself.

There is one more aspect of macros that you will find valuable over your careers.

Engineers often find that they need to manipulate large sets of numbers. Excel is particularly good at this and you can manipulate multiple columns of information. A macro can also manipulate large number of rows and columns without referring to the spreadsheet by storing your values in an array. An array is an ordered set of numbers. For example, the x, y coordinates on a plot, a vector, and a matrix are all examples of arrays. With arrays you can make MS Excel do anything in VBA that you can do with MATLAB, but you may find MATLAB to be faster in many cases.

The example we will use here is to solve two equations with two unknowns. Imagine that we have the following two equations to solve,

2 x + 3 y = 4 5 x + 6 y = 7.

Page 18: Summary of VBA for Scientific Computing 9-25-2013 v1

18

You may remember from second year algebra that you can rewrite these in variable form as a11 x + a12 y= b1 a21 x + a22 y= b2. This set of questions can be solved using Cramer’s rule. If you do not remember Cramer’s rule, you should look it up because it will help you numerically solve equations that you will encounter in this and future engineering classes. One expression of Cramer’s rule for two equations and two unknowns is x = (b1 a22-b2 a12)/(a11 a22- a21 a12) y = (a11 b2-a21 b1) /(a11 a22- a21 a12). We will now write a macro to solve Cramer’s rule for this two variable-two equation system. You can write programs that will do the three equations and three unknowns. The first step in our program is to dimension the array. We will have two arrays: one for the a’s and one for the b’s. Example 12 Sub Cramer_2x2() ‘This program solves two equations and two unknowns given the necessary coefficients. Dim i As Integer Dim a(1, 1) As Double Dim b(1) As Double Dim x As Double Dim y As Double 'we first fill our array from the cells in A1 through B3. For i = 0 To 1 'This for loop cycles through the rows Range("A" & i + 2).Select a(i, 0) = ActiveCell.Value Range("B" & i + 2).Select a(i, 1) = ActiveCell.Value Range("C" & i + 2).Select b(i) = ActiveCell.Value Next 'i 'Now we calculate x and y x = (b(0) * a(1, 1) - b(1) * a(0, 1)) / (a(0, 0) * a(1, 1) - a(1, 0) * a(0, 1)) y = (a(0, 0) * b(1) - a(1, 0) * b(0)) / (a(0, 0) * a(1, 1) - a(1, 0) * a(0, 1)) 'Now we put the results into column E Range("E2").Select ActiveCell.Value = x Range("E3").Select ActiveCell.Value = y End Sub

Page 19: Summary of VBA for Scientific Computing 9-25-2013 v1

19

Notes: 1. The dimensions start from 0 not one so a(1,1) has within it 4 values not one. If we were to

dimension a(2,2) this would have 3 by 3 values for a total of 9 positions in the array. Note that if we wanted to have more dimensions we could. A(1,1,1) would be a three dimension matrix with 8 positions available.

This summary is meant to provide you with an introduction to programming techniques. It is by no means complete. Indeed, a hallmark your career will be continuous learning. If you know that you need some additional functionality. You really have three options. (1) If you can make a spreadsheet do it, a macro can do it as well. Try recording a macro and seeing if you can decipher the code. It is not that complicated as many of the commands are intuitive. This is especially true if you want to teach macros how to plot charts for you, for example. (2) As a matter of practice you should work together with other students and colleagues. This is one of the most effective ways to understand things. They often know things that you do not or can help you put together aspects of the program that you do know but did not realize it. (3) You may also find the following websites helpful in getting started and then advancing your knowledge over the coming weeks, months and years.

1. http://msdn.microsoft.com/en-us/library/ then select Development Tools and Languages, Visual Studio 2005, Visual Studio, Visual Basic

2. www.anthony-vba.kefra.com/vba/vbabasic1.htm. 3. We also have access to Safari books through the university. There you will find several

ebooks that could be valuable. Contact the library for more information on how to access these texts.