EXERCISE 03: Using Visual Basic with EXCEL

Visual Basic ( VB ) is a programming language that allows one to write procedures (programs ) that perform operations on the spreadsheet or perform calculations that return a value.

VB is an Object Oriented language, meaning that it is designed around objects, their properties, and what they do. VBE refers to Visual Basic for Excel and it has a specific library of objects that relate to EXCEL.

For example ActiveSheet is the object by which EXCEL refers to the sheet you are currently working on. ActiveSheet.Name is a property of the active sheet (i.e. its name). ActiveSheet.ActiveCell.Font is the property of the font of the active cell in the active sheet

ActiveSheet.Range(c3).Calculate is an example of a method. It specifies that the contents of cell C3 on the active sheet be calculated.

In EXCEL you can see more of these examples by going to "tools" then to "macro" then to "visual basic". In Visual basic go to "view" and then "Object Browser".

 

VB Procedures that perform operations on the spreadsheet are called SUBs

VB Procedures that perform calculations and return values are called FUNCTIONs

Below is an example of a SUB and a FUNCTION.

Copy and paste these into a visual basic module and then run the sub (by going to tools, macros and then after selecting the macro to run) to see what happens.

 Sub examplesub()

' This is an example of a visual basic sub.

' sub's operate on the worksheet

' In this example the sub will set up a column of

' Cosine values in col. 2 and the index in col. 1

' Declare variables

Dim RowNum As Integer, colnum As Integer, currcell As Range, nextcol As Integer, temp As Single

RowNum = ActiveCell.Row ' intialize row number

colnum = ActiveCell.Column ' intitialize col number

nextcol = colnum + 1

n = 129

Set currcell = ActiveSheet.Cells(RowNum, colnum) ' go to first cell

Set nextcell = ActiveSheet.Cells(RowNum, nextcol) ' get adjacent cell

counter = 1

Do Until counter = n ' do until counter = number of points

currcell.Value = counter

nextcell.Value = examplefunc((2 * 3.14159 * counter / n) - 3.14159)

counter = counter + 1

RowNum = RowNum + 1

Set currcell = ActiveSheet.Cells(RowNum, colnum)

Set nextcell = ActiveSheet.Cells(RowNum, nextcol) ' get adjacent cell

Loop

End Sub

Function examplefunc(xx)

x1 = xx

f1 = x1 - x1 ^ 3 / fact(3) + x1 ^ 5 / fact(5) - x1 ^ 7 / fact(7) + x1 ^ 9 / fact(9)

examplefunc = f1

End Function

Function fact(n)

m = 1

sum1 = 1

Do While m <= n

sum1 = m * sum1

m = m + 1

Loop

fact = sum1

End Function