程序代写代做代考 Excel go algorithm html database C javascript Java CS 200

CS 200
Lecture 06 Excel Scripting
CS 200 Spring 2020 1 02 – Styles

Miscellaneous Notes
Abbreviations
aka Also Known As
CWS Course Web Site (http://www.student.cs.uwaterloo.ca/~cs200)
VBE Visual Basic Editor
intra- a prefix meaning within — thus “intra-cellular” means “within the cell”
inter- a prefix meaning between — thus “inter-galactic” means “between galaxies”
For our purposes, a “macro” and a “script” are the same thing
Optional background reading
Writing Excel Macros, Chapters 3 and 4, (in library) Excel Review (Learn)
Excel Review Exercises (Learn)
A good reference if you’re interested in learning more about Excel Scripting is
Writing Excel Macros (2/e), by Steven Roman
 O’Reilly & Associates, ISBN 0-596-00359-5, © 2002
CS 200 Spring 2020
2
02 – Styles

Administrivia
Please read and highlight the assignment and course notes before lab Assignment 6 is due Monday June 22 at 11:59 pm
Staff suggests reading the assignment before lecture
There are hyper-text commented source files for most of the Excel macros used in this lecture
see “Handouts > Commented Excel Macros” on the course website
Files used in this lecture are on Learn
Week 6: Application Scripting (Excel): Files for Lecture
Today
Scripting in Excel
The Copy Pearl
Remember that the CWS contains material on the pearls
CS 200 Spring 2020
3
02 – Styles

Assumption
You have used a spreadsheet before
You understand a simple program/algorithm
CS 200 Spring 2020
4
02 – Styles

Things to Think About
What are the data objects in a Spreadsheet program?
How does the interface differ from the other applications we have seen so far? What are the efficiencies/deficiencies of the interface?
When would I use a spreadsheet?
How does a spreadsheet compare to a database?
How would macros be useful in other applications we have seen so far?
CS 200 Spring 2020
5
02 – Styles

Application Scripting in Excel
What is “(intra-)application scripting”?
a way to automate lengthy manual procedures a way to customize / extend an application
a way to create a different interface “programming in the small”
Recording a script
“record” a manual procedure (once) and “play it back” many times sort of like a player piano
record a script to learn how to do something look up terms in the script as necessary
“anything you can do manually, you can script” — & more
Edit a recorded script
to make it more general
to eliminate unnecessary steps to wrap a loop around it
to do something similar
CS 200 Spring 2020
02 – Styles

Why Scripting in CS 200?
Most major apps have some sort of scripting
eg Word, Excel, Photoshop, FileMaker… eg system-level macro languages
hooked to key presses or menu selection (eg iKey, UI Actions) or sometimes to user-defined palettes
to move data between apps & tell those apps how to process the data (eg AppleScript, VBA)
eg JavaScript in HTML pages, DreamWeaver, Acrobat…
— in fact, some have more than one!
— Photoshop supports three (or four, depending on how you count)
Scripting can save you a LOT of work
CS 200 Spring 2020
7
02 – Styles

Automating SpreadSheet Creation — Format with a Macro (1)
CS 200 Spring 2020
8
02 – Styles

Automating SpreadSheet Creation — Format with a Macro (2)
The macro

‘ Rule_Left_and_Bottom Macro
‘ Macro recorded 10/12/95 by John C. Beatty

Sub Rule_Left_and_Bottom()
Selection.BorderAround _
Weight := xlThin, _
ColorIndex := xlAutomatic
Selection.Borders(xlRight).LineStyle = xlNone
Selection.Borders(xlTop).LineStyle = xlNone
End Sub
Note the comments, introduced by the character ‘

— anything from there to the end of the line is ignored

(add your own to remind yourself later of things you figure out)
This example illustrates speeding spreadsheet development
macros are easy to read & usually you can RECORD what you want to do,

or something close to it, and just edit the recording
look up terms you don’t know with online help (in the VBE environment)

eg select a term like ColorIndex and press the help key
CS 200 Spring 2020
9
02 – Styles

Automating Use Of A Spreadsheet — Sort Marks
This illustrates speeding the use of a spreadsheet
CS 200 Spring 2020
10
02 – Styles

Sort Marks — By Name
Sub Sort_By_Name2()
Range(“B3:D14”).Select
Selection.Sort
CS 200 Spring 2020
11
02 – Styles
_
:= Range(“C3”), _
:= xlAscending, _
:= xlGuess, _
OrderCustom := 1, _
MatchCase := False, _
Key1
Order1
Header
Orientation := xlTopToBottom
Range(“A1”).Select
End Sub
“_” means “the statement continues on the next line”
It’s pretty easy to guess what each piece of the Selection.Sort
statement does, right?

Sort Marks — By Mark
Sub Sort_By_Mark2()
Range(“B3:D14”).Select
Selection.Sort
_
:= Range(“D3”), _
:= xlDescending, _
:= xlGuess, _
OrderCustom := 1, _
MatchCase := False, _
Key1
Order1
Header
Orientation := xlTopToBottom
Range(“A1”).Select
End Sub
CS 200 Spring 2020
12
02 – Styles

Extending Excel — F to C Conversion
The macro
Function FtoC( fTemp )
FtoC = (fTemp – 32) * 5 / 9
End Function
illustrates extending an application by means of a macro
Note the use of “Function” instead of “Sub”
“functions” return a value (the value assigned to their name) “subroutines” don’t — they just “do something”
FtoC can be used anywhere a built-in Excel function 
 can be used
See also “Marks to Grades” in
Week 6 / Files for Lecture: Excel Macros
Sub Sort_By_Mark2() Range(“B3:D14”).Select… …
End Sub
CS 200 Spring 2020
13
02 – Styles

Making a spreadsheet look like a hand-built app
CS 200 Spring 2020
14
02 – Styles

Excel’s Scripting Environment
Selecting Macros… opens the dialog shown above right Note the “Record New Macro…” menu item
CS 200 Spring 2020
15
02 – Styles

Editing a Macro
To edit a macro
click the Edit button in the Macros dialog
or select “Visual Basic Editor” from the menu
 shown on the previous slide
Note the new menu bar, & especially the View menu in it
All the active menu items are interesting
CS 200 Spring 2020
16
02 – Styles

The VBE Environment (The Big Picture)
CS 200 Spring 2020
17
02 – Styles

Excel vs the Visual Basic Editor
A bit like two programs wrapped as one

— one dock icon, but with different menu bars and different windows/palettes
in the VBE, click on a spreadsheet to “flip back to Excel”
 (or select “Excel > Close and Return to Microsoft Excel” !)
in Excel, click on a Code window to 

“flip back to the VBE”

(or select “Tools > Macros > Visual Basic Editor”)
T
CS 200 Spring 2020
18
02 – Styles

Excel’s Scripting Environment
The Project Explorer window
Recorded macros go into “Modules”
“Sheets” & “ThisWorkbook” can hold macros, too
Double-click any of the three to edit its macros
Suggestion: keep all your macros in modules

—otherwise you must refer to them as Sheet1.macroName, etc
The Properties window
Click on one of the entries in the Projects window
Its “properties” are displayed in the Properties window
You can change many of them;

you won’t need to for the assignment.
CS 200 Spring 2020
19
02 – Styles

“Objects” in Excel Macros
Just about everything you see in a workbook is an “object”
There is a natural hierarchy to objects
You can have multiple instances

of everything except the Application
These are Excel’s “application data objects”
(remember the Model pearl?)
A “module” is for holding macros (aka “scripts”) think of it as a document

containing multiple macro definitions in the VBE: Insert > Module and type
or … a module is created automatically
 when you record a macro
See Chapter 5 of The Microsoft Excel Visual Basic User’s Guide on “Working with Objects in Visual Basic” (pp 65–84),
which is reprinted in the course notes, for more on objects in Excel.
Application
Workbook
Worksheet
Chart Module
Range Range
Cell Cell
Cell
CS 200 Spring 2020
20
02 – Styles

Objects
Objects have “properties” like “Color,” “Value,” “Font” that you can read or set in macros
sometimes a property is just a value (eg 2)
sometimes a property is another object
Objects have “methods” like “ClearContents,” “Sort,” “Worksheets” that cause something to be done to or with the object
a “method” is just another kind of built-in function or subroutine
 that does something to or with the object it’s attached to
methods often have “parameters” (aka “arguments”) — information they need
— just like built-in Excel functions
eg C4, ForEx, and 2 in VLOOKUP( C4, ForEx, 2 )
“Member” is programmer-speak for both properties and methods All objects of a particular kind are a “class” of objects
CS 200 Spring 2020
21
02 – Styles

Referring to an object or property
Referring to an object or property
EG: Application.Worksheets(“Visa”) _
 .Range(“Stmt”).Font.Name = “Helvetica”
Here
Application is an object
Worksheets() is a method (that returns a Worksheet object) Range() is a method (that returns a Range object) Font is a property (whose value is a Font object) Name is a property (a string)
The () surround a method’s parameters — information the method needs to do its thing.
You can use the Properties Window
 to set an object’s properties manually
These arguments are the names that appear on worksheet tabs
Says that the statement is continued on the next line
CS 200 Spring 2020
22
02 – Styles

Especially Useful Properties
Application.ActiveWorkbook
you can just write ActiveWorkbook for the frontmost workbook
Application.ActiveSheet
you can just write ActiveSheet
for the worksheet whose tab was last clicked
Application.ActiveCell
you can just write ActiveCell
for the currently selected cell
And usually you can omit Application.ActiveSheet
eg Range… instead of Application.ActiveSheet.Range… eg Selection… instead of …
How do you find out about objects, properties and methods?
record a macro, then highlight a method or property name & press the help key
 ie if you see something and wonder about it
use the “object browser”

if you want to go looking to see, for example, if worksheets have a particular property
Sub Sort_By_Mark2()
Range(“B3:D14”).Select
Selection.Sort
_
:= Range(“D3”), _
:= xlDescending, _
:= xlGuess, _
OrderCustom := 1, _
MatchCase := False, _
Key1
Order1
Header
Orientation := xlTopToBottom
Range(“A1”).Select
End Sub
CS 200 Spring 2020
23
02 – Styles

Cell References in Excel Worksheets & Macros
Before row/column insertions
The macros
MyLiteralTotal() MyNamedTotal()
after inserting a new column

at the left edge of the spreadsheet
 — notice which total is correct!

— and why!
After row/column insertions
So … when you insert/delete rows/columns
Excel updates all cell references in a worksheet, literal references (“E43”, “$R$13”), range definitions, etc, but the text of macros is untouched
The moral … you nearly always want to use named ranges in macros
CS 200 Spring 2020
24
02 – Styles

Cell References in Excel Macros
Consider the Sort Marks example with these macros:
Suppose we added a student, or moved the list.
 Would the macros still work properly?
T
Sub Sort_By_Name()
Range(“B3:C14”).Select
Selection.Sort
Key1
Order1
Header
OrderCustom := 1,
MatchCase := False,
Orientation := xlTopToBottom
Range(“A1”).Select
End Sub
Sub Sort_By_Mark()
Range(“B3:C14”).Select
Selection.Sort
_ _ _
Key1
Order1
Header
Orientation := xlTopToBottom
Range(“A1”).Select
End Sub
_
:= Range(“B3”), _
:= xlAscending, _
:= xlNo,
_
:= Range(“C3”), _
:= xlDescending, _
:= xlNo, _
OrderCustom := 1, _
MatchCase := False, _
02 – Styles
CS 200 Spring 2020
25

Doing Sort Marks Correctly
Use a named range instead of explicit literal cell references
What if I want to add a new student?
adding in the middle of a named range adding to the end of a named range
use a final blank row?
would the average be correct?
This is another instance of “indirection”
Sub Sort_By_IDnumber2()
Range(“theData3”).Select
Selection.Sort _
Key1
Order1
Header
OrderCustom := 1, _
MatchCase := False, _
Orientation := xlTopToBottom
Range(“A1”).Select
End Sub
:= Range(“theData3”).Range(“A1”), _
:= xlAscending, _
:= xlGuess, _
CS 200 Spring 2020
26
02 – Styles

Watching Your Macros Run
This dot marks a “breakpoint”
CS 200 Spring 2020
27
02 – Styles

Debugging (The Big Picture)
CS 200 Spring 2020
28
02 – Styles

Using the Debugger
Set a breakpoint
by clicking in the left margin

to halt a macro when it gets to that statement
“clear” the breakpoint by clicking again in the left margin
Use
? variableName in the Immediate Window to display the value of the variable
Use
Debug > Step Into (does dive into functions or subroutines)
 Debug > Step Over (doesn’t dive into functions or subroutines)
 to execute one statement and stop again
Use
Run > Continue

to turn the macro loose
The Visual Basic Editor’s Debug toolbar has buttons for all of these

(View > Toolbars… > Debug)
CS 200 Spring 2020
29
02 – Styles

Attaching a Macro to a Spreadsheet Button
Draw a button after selecting on the Developer Ribbon Ctrl-click on the button to open the Assign Macro dialog Select and OK the desired macro
CS 200 Spring 2020
30
02 – Styles

Putting It Together: Tools > Macro > Macros…
To
run a macro delete a macro edit a macro
And via the Options… button
you can attach a macro to a key

(or key combination) on the keyboard
CS 200 Spring 2020
31
02 – Styles

Relevant Programming Concepts
Variables and declarations Assignment statements Sequential execution
Loops
initialization
termination test
changing the loop control variable(s)
If–then–else statements Subroutines and functions
parameters (aka arguments)
Debugging
interactive source-level debugging
CS 200 Spring 2020
32
02 – Styles

The Assignment For This Week
Given the raw data, duplicate the functionality of this spreadsheet
CS 200 Spring 2020
33
02 – Styles

This Week’s Assignment is “Layered”
Trivial formulas
eg for Actual Balance
Simple formulas
eg for Statement Balance or Next Transaction Number
Not quite so simple formulas
eg for the CD Charge cell for US$ purchases
Simple macros
eg for scrolling, sorting, or filtering
Not quite so simple macros
eg for making new entries
Note that you can create all of these macros by recording them, you do not need to use VBA
CS 200 Spring 2020
34
02 – Styles

Strategy For The Assignment
Start with the simple stuff
and proceed in stages towards the more difficult
Test as you go
Make a copy of your spreadsheet at each successful stage
eg, when you have the simple formulas working,
ie, squirrel a copy of that away

in case you totally muck up the next step
 and want to start over on it

(remember “backups”?)
CS 200 Spring 2020
35
02 – Styles

Strategies For Working With Macros
Record
•to learn how to do something •to build a macro faster
Edit recorded macros to customize / elaborate them
Use on-line help and the object browser

to find object names, properties, & methods that you need
Experiment
•with toy macros & documents
•eg the workbooks used in lecture (see Learn Week 6: Application Scripting (Excel) /
Files For Excel Scripting)
Use the debugger
• to understand what your macros are doing!
Save everything you do, and include comments (they start with the single quote
character ‘ )
CS 200 Spring 2020
36
02 – Styles