Upload
others
View
7
Download
0
Embed Size (px)
Citation preview
1
GEEN 1300Introduction to Engineering Computing
Class meeting #15Wednesday, Oct 14th
Excel & Visual Basic for Applications (VBA)
accessing a spreadsheet range directly from VBA
1Homework #7, posted, due next Wednesday
cell ranges as arguments to functions
creating array variables in VBA
Array Data Structures
Example: a set of pH measurements on treated wastewater
6.2 7.1 7.2 7.6 7.1 7.5 7.0 8.57.0 6.5 7.0 6.8 7.7 7.8 8.1
These measurements can be stored on the spreadsheetThese measurements can be stored on the spreadsheetand they can be stored in an array variable in VBA.
In either case, it is convenient to refer to the set ofmeasurements by a single identifier and then refer toindividual measurements using a subscript.
2
pH4 the 4th item in the pH array
This type of referencing is handled differently in Excel andVBA and cross-referencing from Excel to VBA is distinctalso.
2
Accessing a spreadsheet range directly from VBA
Note: It is not necessary toote t s ot ecessa y toreference a particularworksheet since a rangename is global throughoutthe workbook.
The "ActiveCell" is at the topof the "Selection" and its value
3
can be referenced in VBA by
Note: "Value" is the defaultproperty and can be left out
Accessing a spreadsheet range directly from VBA
What then is the result of
What if we want the value inthe cell below the ActiveCell?
What if we want toh th A ti C ll
4
No. of rows "away"from the current row No. of columns
"away" from thecurrent column
change the ActiveCellto the cell below thecurrent ActiveCell?
3
Accessing a spreadsheet range directly from VBA
Moving the ActiveCell to the end of a range of filled cells(record a macro to see how this is done)
Selecting from the ActiveCell to the endf f fill d ll
5
of a range of filled cells
(again, figure this out by recording a macro)
Accessing a spreadsheet range directly from VBA
Selecting an entire range of cells (Ctrl - * in Excel)
Determining the size (no.of rows and columns) of aselected range of cells
6
This is important in writing VBA code for an arbitraryselected range of cells.
4
Cell ranges as arguments to functions
It is common to want to write a function that makescalculations for one or more arguments that are rangesof cells.
General pattern:General pattern:
Invoke function on spreadsheet with pH argument:Trace execution of function with
7
breakpoint -- check value of nRows:
nRows = 15
Cell ranges as arguments to functionsExample: Find the second largest item in a
range of cellsNote: We should take advantage of Excel's (not VBA's)
Max function.
find the maximumfind the maximumvalue in DataRange
to start, set the second maximumvalue = the first value in DataRange
8
use nested For-Next loops to go through all theelements of DataRange -- take no action whenthe MaxVal is found -- check all other values againstthe current second maximum, and, if a new secondmaximum is found, update the stored value
5
Cell ranges as arguments to functions
Simple example: Find the second largest item in arange of cells
9
Creating array variables in VBA
allocates space for the array in VBA,variant type
assigns the value of 3 to an element of X
Track what’s going on using the Locals windowTrack what s going on using the Locals window
10
Notice that elements 0 to 10 (11 total) have beenallocated to X
6
Creating array variables in VBA
So, when you Dim X(10), the arrayorigin is 0
Shows that element 1
11
Expand X in the Locals Windowby clicking on the + next to it
Shows that element 1of X has the value 3
Creating array variables in VBAUse the declaration Option Base 1
to force the array origin to be 1
12
Now, only 10 elements, indexed 1 to 10have been allocated to X
7
Creating array variables in VBA
13Now, origin of X is 1
Creating array variables in VBA
Two-dimensional array(rows and columns, like a matrix, correspondsto a rectangular range of cells on the spreadsheet)
14Shows 1 to 4, 1 to 4
8
Creating array variables in VBATwo-dimensional array
By expanding X, then row branch 2,note value of 3 assigned to elementin row 2, column 3
15
Creating array variables in VBA
Creating arrays with variable dimensions(when you don’t know an integer value or values
to put into the Dim statement for the array)
Start by “Dim”-ing array X as emptySta t by g a ay as e pty
Get value of allocation for X fromsomewhere, here the user
Use the value stored in n to“ReDim” the X array
You can “ReDim” an array many times during
16
You can “ReDim” an array many times duringa VBA program, thus creating a dynamic allocationof space for the array.
9
Cell ranges as arguments to functions
Example application: compute the median absolute deviation(MAD)
The MAD of a set of data is found in the following way:
1) find the Median of the data set (sort the data and pickthe one in the middle -- for even-numbered set,average the two in the middle)
2) calculate the absolute values of the differences betweenthe data and the Median value of the data
17
3) find the Median of that set of absolute-value differences
Note: Excel (not VBA) has a function that computes theMedian, so we will want to take advantage of that.
Cell ranges as arguments to functionsExample application: compute the median absolute deviation
(MAD)
declare array forabsolute deviations
begin
RC = 1RC >R
Flowchart
AbsDev
get nRows & nColsfor DataRange
allocate space forAbsDev(nRows,
nCols)
nRows?
RC = RC + 1
CC = 1CC >nCols?
CC = CC + 1
use Excel’s Median
18
use Excel’s Medianfunction to get
DataMed
AbsDev(RC,CC) =|DataRange(RC,CC)-
DataMed|
function to getMAD as median of
AbsDev array
end
10
Cell ranges as arguments to functionsExample application: compute the median absolute deviation
(MAD)necessary so arraysubscript origin is1,1
19
Referencing array elements on the spreadsheet
array of cells named “pH”
Use of INDEX function toselect one element ofpH array with row and
l i di
20
column indices
11
Referencing array elements on the spreadsheet from VBAborrowing the Index function from Excel
Transferring the array from the spreadsheet to a VBAarray variable
21
When assigningan object, mustuse the Setcommand
Building an array in VBA from user input
This is called a “sentinel” value
22
The keyword “Preserve” extends the size of the arrayfor each data value entered, without wiping out theprevious values entered
12
Once you are able to program VBA to accessranges of cells and treat them as arrays, orto create arrays within VBA, the possibilitiesfor programming applications are virtuallyendless.endless.
These include
all kinds of user-defined functions thatarise from needs, and where Excel hasno built-in function
23
vector-matrix math calculations
VBA manipulations of tables of data that cansave hours of spreadsheet operations