Introduction to Visual BASIC - Research and Teaching Methods - Lab, Study notes of Research Methodology

The goal of this course is to pass on to new graduate students fundamentals of graduate research with an emphasis on biological systems engineering, and, college instruction. Keywords in this lab manual are: Introduction to Visual Basic, Scope of Variables, Creating References, Et Results, Penman-Monteith Model, Root Mean Square Error, Spreadsheet Program, Evapotranspiration, Dynamic Link Library

Typology: Study notes

2012/2013

Uploaded on 10/03/2013

abani
abani 🇮🇳

4.4

(34)

81 documents

1 / 4

Toggle sidebar

This page cannot be seen from the preview

Don't miss anything!

bg1
1
Introduction to Visual BASIC for Applications: Part II
Scope of Variables
An important consideration when writing programs is the scope of the variables, functions and
subroutines. When a variable is defined inside a function or subroutine, it exists only inside that function or
subroutine. When that function or subroutine is not active, the value of the variable is not retained or
accessible by other functions or subroutines. We sometimes want variables to retain their values and be
available to other functions or subroutines. To do this we declare them outside the function or subroutine so
they become available to any function or subroutine in the Module. If certain variables need to be available
to functions and subroutines outside the Module, they can be declared using the key word Public, but this
is usually not a good idea. Why?
Becoming Familiar with the Use of Objects
Until this point you have learned basic aspects of the use of macros and of programming with VB. Now
it is worthwhile to turn our attention to some “big picture” aspects of programming with VB, particularly the
use of objects. When writing applications using VB in Excel it is helpful to think in terms of objects. Excel
objects include the Excel application itself, a workbook, a worksheet in a workbook, a range in a worksheet,
a chart sheet, a chart on a chart sheet, and many other components. These objects (more than 100) are
organized following an object hierarchy (Excel’s object model), which can be manipulated by using Visual
Basic for Applications (VBA).
In Excel’s object model, as may be the case in other applications, objects are containers for other objects.
Excel is an object called “Application” and contains other objects such as “Workbook” objects. The
contained object is referred to as a member object. The position of a member object in a hierarchy is
specified using a period as a separator between the container object and the member. Thus, a workbook
named “Mybook.xls” can be referred to as
Application.Workbooks(“Mybook.xls”)
Similarly, the worksheet “Sheet1” in such a workbook can be referred to as
Application.Workbooks(“Mybook.xls”).Worksheets(“Sheet1”)
If the specific reference to an object is omitted, the current active object is used as default. For example,
if workbook “Mybook.xls” and worksheet “Sheet1” are active, you can directly refer to a given cell to store
a value as, e.g., [A5] = 100.5. If you are writing code on a module associated with a given workbook, this
workbook is then active by default. You can activate “Sheet1” as shown before by simply stating
Woksheets(“Sheet1”).Activate.
In addition to Excel objects that you can use and manipulate, you can create your own objects, which
provides a convenient way to write your programs. All objects are defined by a class, which is a template
from which objects can be created. A “class module” is a special type of VB module that you can insert into
a project. To do this, choose “Insert/Class Module” from the VB editor. The code that you write in a Class
Module cannot be executed directly. You must “instantiate” an object of this class using a regular Module
sheet.
One characteristic of objects is that they may have Properties, Methods, and Events. Object properties
are attributes that describe the object. They represent the data of an object (although they are not the data
pf3
pf4

Partial preview of the text

Download Introduction to Visual BASIC - Research and Teaching Methods - Lab and more Study notes Research Methodology in PDF only on Docsity!

Introduction to Visual BASIC for Applications: Part II

Scope of Variables

An important consideration when writing programs is the scope of the variables, functions and

subroutines. When a variable is defined inside a function or subroutine, it exists only inside that function or

subroutine. When that function or subroutine is not active, the value of the variable is not retained or

accessible by other functions or subroutines. We sometimes want variables to retain their values and be

available to other functions or subroutines. To do this we declare them outside the function or subroutine so

they become available to any function or subroutine in the Module. If certain variables need to be available

to functions and subroutines outside the Module, they can be declared using the key word Public , but this

is usually not a good idea. Why?

Becoming Familiar with the Use of Objects

Until this point you have learned basic aspects of the use of macros and of programming with VB. Now

it is worthwhile to turn our attention to some “big picture” aspects of programming with VB, particularly the

use of objects. When writing applications using VB in Excel it is helpful to think in terms of objects. Excel

objects include the Excel application itself, a workbook, a worksheet in a workbook, a range in a worksheet,

a chart sheet, a chart on a chart sheet, and many other components. These objects (more than 100) are

organized following an object hierarchy (Excel’s object model), which can be manipulated by using Visual

Basic for Applications (VBA).

In Excel’s object model, as may be the case in other applications, objects are containers for other objects.

Excel is an object called “Application” and contains other objects such as “Workbook” objects. The

contained object is referred to as a member object. The position of a member object in a hierarchy is

specified using a period as a separator between the container object and the member. Thus, a workbook

named “Mybook.xls” can be referred to as

Application.Workbooks(“Mybook.xls”)

Similarly, the worksheet “Sheet1” in such a workbook can be referred to as

Application.Workbooks(“Mybook.xls”).Worksheets(“Sheet1”)

If the specific reference to an object is omitted, the current active object is used as default. For example,

if workbook “Mybook.xls” and worksheet “Sheet1” are active, you can directly refer to a given cell to store

a value as, e.g., [A5] = 100.5. If you are writing code on a module associated with a given workbook, this

workbook is then active by default. You can activate “Sheet1” as shown before by simply stating

Woksheets(“Sheet1”).Activate.

In addition to Excel objects that you can use and manipulate, you can create your own objects, which

provides a convenient way to write your programs. All objects are defined by a class, which is a template

from which objects can be created. A “class module” is a special type of VB module that you can insert into

a project. To do this, choose “Insert/Class Module” from the VB editor. The code that you write in a Class

Module cannot be executed directly. You must “instantiate” an object of this class using a regular Module

sheet.

One characteristic of objects is that they may have Properties , Methods , and Events. Object properties

are attributes that describe the object. They represent the data of an object (although they are not the data

itself). With properties, we can write code to store data into, and retrieve data from, the class (remember, you

write the code in a Class Module, but you write code on a Module to create and use an object of a given

class). Methods are subroutines and functions that we program within the object to manipulate data and

provide services to other objects. An object can also raise events , e.g., to provide feedback on the status of

the object while executing the code, such as a user clicking on a button or changing a text box.

The following code implements a simple accumulator class. This class has one property (Multiplier) and

two methods (one subroutine and one function). Remember that this code must be written in a Class Module.

Option Explicit Private Current_Multiplier As Single Dim Accumulator As Single ’The following statements set the value of the property “Multiplier” PropertyCurrent_Multiplier Let Multiplier(Multiplier_Value = Multiplier_Value As Single) End Property ’The statements below retrieve the value of the property “Multiplier” Property Get Multiplier() As Single MultiplierEnd Property = Current_Multiplier ’The following subroutine and function are methods SubAccumulator Accumulate(X = Accumulator As Single) + X * Multiplier End Sub FunctionGetAccumulation GetAccumulation() = Accumulator End Function

This code provides a “template” for an object. To make use of this code, objects of this class must be

created (this is referred to as “creating an instance” of this class). The following is a piece of code (written

in a regular Module) that instantiate two objects of this class. This is provided as an example so that you are

exposed to this concept.

Option Explicit Sub CalculateAccumulation() ’InstantiateDim MyObject twoAs Newobjects MyClass of MyClass Dim AnotherObject As New MyClass ’Declare local variables DimDim Cumulative_ValueCheck_Multiplier AsAs SingleSingle ’Set the Multiplier property MyObject.MultiplierAnotherObject.Multiplier = (^2) = 3

’ThisCheck_Multiplier is to check =that MyObject.Multiplier the Multiplier property was properly set

Lab 3 Assignment

1. In this exercise, we will use, with slight modification, an existing code to calculate evapotranspiration

(ET) using the Penman-Monteith model (P-M ET). The instructor will provide the code, which is written

in Visual Basic for Applications (in Excel) using an object-oriented approach. Using output from this

program, you will be asked to calculate the coefficients of a simplified ET model using Solver, a built-in

tool of Excel. ( 20 pts ) ( Note: tasks (i) thru (v) should be completed during the lab while task (vi) and

Problem 2 are take-home assignments. Only task (vi) and Problem 2 need to be submitted .)

(i) Study the input and output worksheets and the VBA code attached to the spreadsheet program

provided by the instructor.

(ii) Write an output class and instantiate an object of this class on the main module. Your code should

output the following columns: Day of the year (DOY), P-M ET , maximum temperature ( Tmax ),

minimum temperature ( Tmin ), average temperature ( Tavg ), and potential solar radiation ( Ro ).

(iii) In the output worksheet, add a column to calculate the following equation for each DOY:

(iv) Compare ET results from using the Penman-Monteith model and the simple ET equation (Eq 1),

respectively, by calculating the Root Mean Square Error ( RMSE ) with a set of given initial values

of the coefficients a and b

where O i and P i are the observed and predicted values and N is the number of data pairs.

(v) Use Solver to optimize the coefficients using the RMSE as objective function to be minimized.

( Note: first make sure that the feature “Add-Ins” under Tools/Add-Ins is activated .)

(vi) Now, combine all three years of P-M ET , temperature (maximum, minimum, and average), and

potential solar radiation data into one set of data. Use Solver to obtain optimized coefficients of a

and b in Eq 1 for this newly combined data set. Then apply the coefficients to each of the three years

of data (1996, 1997, and 1998) separately. Report the RMSE for each year, together with a graph

displaying the agreement (or lack of) between the ET values predicted using the P-M model and the

simplified approach, respectively.

2. For your graduate research ( 5 pts )

(i) Identify the major processes involved in your research problem and state what type of processes they

are, physical, chemical, or biological, or their combinations.

(ii) Describe the challenges or difficulties in tackling your research problem by describing the challenges

or difficulties of understanding specific processes or components in the processes.