1
CS 106Computing Fundamentals IIChapter 17Introduction To VBA
Herbert G. Mayer, PSU CSHerbert G. Mayer, PSU CS
status 6/30/2013status 6/30/2013
Initial content copied verbatim fromInitial content copied verbatim from
CS 106 material developed byCS 106 material developed by
CS professors: Cynthia Brown Robert MartinCS professors: Cynthia Brown Robert Martin
2
Syllabus
Not An Introduction to ExcelNot An Introduction to Excel
Idea of ObjectsIdea of Objects
EventsEvents
But First: WarningBut First: Warning
Security SettingsSecurity Settings
Macro RecordingMacro Recording
Look at CodeLook at Code
What is Code?What is Code?
3
Not An Introduction to Excel
Assumption: you have basic familiarity with ExcelAssumption: you have basic familiarity with Excel
If you dont, or you need review, you can get startedby going through the Introduction to Excel in the firstmoduleIf you dont, or you need review, you can get startedby going through the Introduction to Excel in the firstmodule
4
Idea of Objects
VBA is built on the idea that workbook is ahierarchy of objectsVBA is built on the idea that workbook is ahierarchy of objects
An object can contain other objectsfor example, aworkbook contains worksheets, and the worksheetscontain cellsAn object can contain other objectsfor example, aworkbook contains worksheets, and the worksheetscontain cells
An object can have propertieslike the value in cellor the font used in cellAn object can have propertieslike the value in cellor the font used in cell
An object can have methodswhich are actions thataffect the objectAn object can have methodswhich are actions thataffect the object
5
Events
Objects can have events: for example, opening aworkbook is an event; so is clicking on cellObjects can have events: for example, opening aworkbook is an event; so is clicking on cell
Our VBA programs perform tasks when eventshappenOur VBA programs perform tasks when eventshappen
The spreadsheet or Excel form we are working withwill serve as the user interface, and events likeclicking button will trigger the performance of taskThe spreadsheet or Excel form we are working withwill serve as the user interface, and events likeclicking button will trigger the performance of task
6
Macros
VBA programs are called macros. The simplest wayto get started writing macros is to record one. Thisfeature lets VBA produce code based on actions youperform while recordingVBA programs are called macros. The simplest wayto get started writing macros is to record one. Thisfeature lets VBA produce code based on actions youperform while recording
Well go through an exampleWell go through an example
This is not proper way to create macros other thanreally simple ones, especially if formulas are involvedThis is not proper way to create macros other thanreally simple ones, especially if formulas are involved
It is good for getting an idea of what kind of code towrite to perform particular taskIt is good for getting an idea of what kind of code towrite to perform particular task
7
BUT FIRST: A Warning!
Macros can be dangerous! They can change files onyour computer, send emails to everyone in youraddress book, and insert spyware; hackers love themMacros can be dangerous! They can change files onyour computer, send emails to everyone in youraddress book, and insert spyware; hackers love them
Caveat: NEVER run macros from an un-trustedsourceCaveat: NEVER run macros from an un-trustedsource
The default setting on the Macro Security control (inWindows) is good one: you have to authorizemacros before you can run themThe default setting on the Macro Security control (inWindows) is good one: you have to authorizemacros before you can run them
8
Heres the control for the securitysettings (Windows version)
Macro Security control
9
Get to Trust Center Window byclicking the Macro Security control
This defaultsetting is thecorrect one forus
You will have to check a box toenable macros to run wheneveryou open a workbook withmacros in it.
You will also have to save yourworkbook as a Macro-enabledWorkbook with extension.xlsm
10
Macro Security (Mac version)
Get this window by clickingPreferences
under the Excel menu
11
Be sure that the warn before opening a file
that contains macros box is checked
12
Recording a Macro (Windows)
There are two macro recordingbuttons as shown by the arrows.You can push either one to beginrecording.
13
Relative References Control
The Use Relative Referencesbutton lets you choose whether touse relative or absolute referenceswhen recording your macro.
The default is to use absolutereferences.
14
Macro Recording on the Mac
Macro recording button
Relative references control
Note these are on the Developer tab
15
Recording a simple macro
This macro is in the workbook CopyCols.xlsm postedon the websiteThis macro is in the workbook CopyCols.xlsm postedon the website
Using absolute references, well copy one column toanotherUsing absolute references, well copy one column toanother
The example is shown in Windows; doing it on theMac is quite similarThe example is shown in Windows; doing it on theMac is quite similar
16
The Worksheet Before WeRecord
I used R1C1 in Row 1Col 1 etc. so you cansee where data comesfrom when we copy it.
17
Heres the screen we get when wepush the Record Macro Button
I gave it a
descriptive
name.
If you give it a shortcut key,
make sure it doesnt conflict
with an important one
Be sure to
describe what
it does
Our usual
option
After you push OK, recording begins
18
You can see the Mac version has basically the same interface as the
Windows version
19
In the middle of recording…
Clickhere
whendone
[On the Mac, just click the record button again
to stop]
20
To run Macro Push Macro Button
Highlightthe macroyou wantto run andpush therun button
21
Add a Button to Run the Macro(Windows)
On the developertab, under Insert,click the littletriangle. The iconfor a button is at theupper left underForm Controls
22
Add Button to Run the Macro (Mac)
On the Mac, the controls you can add
are in the ribbon
23
Click to put Button onto Worksheet
Put it about where you want it, but you can alwaysmove it laterPut it about where you want it, but you can alwaysmove it later
The next step is to associate the button with themacroThe next step is to associate the button with themacro
The screen on the next page will come upautomaticallyThe screen on the next page will come upautomatically
24
Highlight Macro Name, Click OK
Before
After
25
Click on the button to get a cursor totype meaningful text
26
Final Product
I had to make thebutton longer to holdthe text I wanted
27
Lets Look at the Code!
Click the Macrosbutton at theupper left of thedeveloper tab andthen click the Editbutton. This willtake you to theVBA Editor.
28
The VBA Window (Windows)
Project
Window
Properties
Window
CodeWindow
Lets just look at the codefor now
29
Code Explanation
Sub CopyAtoD()Sub CopyAtoD()
''
CopyAtoD MacroCopyAtoD Macro
Copy Column to Column DCopy Column to Column D
''
''
    Columns("A:A").Select    Columns("A:A").Select
    Selection.Copy    Selection.Copy
    Columns("D:D").Select    Columns("D:D").Select
    ActiveSheet.Paste    ActiveSheet.Paste
End SubEnd Sub
Sub is a workingpiece of code, a Macro.This is the code for ourMacro CopyAtoD
A line that starts with a  isa comment. It is not part ofthe code. VBA used ourdescription for thiscomment. The editorcolors comments green
The End Sub closes offthe code for thissubroutine. Sub and EndSub are key words forthe editor; it colors themblue
30
The Code Body (1)
    Columns("A:A").Select    Columns("A:A").Select
    Selection.Copy    Selection.Copy
    Columns("D:D").Select    Columns("D:D").Select
    ActiveSheet.Paste    ActiveSheet.Paste
A range of columns(which here is just onecolumn, A) is anobject. It has a methodSelect. This codeactivates the methodto select that column
31
The Code Body (2)
    Columns("A:A").Select    Columns("A:A").Select
    Selection.Copy    Selection.Copy
    Columns("D:D").Select    Columns("D:D").Select
    ActiveSheet.Paste    ActiveSheet.Paste
A selection is also anobject. It has a methodcalled Copy. This linecopies the selection(column A) and puts iton the clipboard
32
The Code Body (3)
    Columns("A:A").Select    Columns("A:A").Select
    Selection.Copy    Selection.Copy
    Columns("D:D").Select    Columns("D:D").Select
    ActiveSheet.Paste    ActiveSheet.Paste
Change the selectionfrom Column A toColumn D
33
The Code Body (4)
    Columns("A:A").Select    Columns("A:A").Select
    Selection.Copy    Selection.Copy
    Columns("D:D").Select    Columns("D:D").Select
    ActiveSheet.Paste    ActiveSheet.Paste
Here the sheet is theobject when we do apaste. This pastes theinformation on theclipboard to theselected place on theactive worksheet
34
What Is Code?
The code is series of instructions to ExcelThe code is series of instructions to Excel
The instructions are performed in the order given inthe code, so order is critically importantThe instructions are performed in the order given inthe code, so order is critically important
The idea of coding is to write instructions to makeExcel do what you want it to doThe idea of coding is to write instructions to makeExcel do what you want it to do
35
Saving the Workbook: Save asMacro-Enabled Workbook!
36
When you reopen, click the Optionsbutton and choose Enable thisContent
37
One More Macro
Well do the same macro, but this time with the UseRelative References option selectedWell do the same macro, but this time with the UseRelative References option selected
Inaming this one Copy4BackInaming this one Copy4Back
So will click the relative references option, clickrecord macro, and give the macro name. Then willselect Column D, select Column A, copy Column toColumn D, and stop recording. Then we make abutton for the new macroSo will click the relative references option, clickrecord macro, and give the macro name. Then willselect Column D, select Column A, copy Column toColumn D, and stop recording. Then we make abutton for the new macro
38
Heres what it looks like
39
After Clicking Copy A toD
If I select Column Dand click Copy 4Back, I get the samething. But if I selectColumn E and clickCopy 4 Back, I getthe next picture.
(I erased Column Dfirst.)
40
Column B was Copied!
… because Ihad relativereferencesturned on
41
Slight Problem
If you look at the code you will see probably shouldhave named my macro Copy3BackIf you look at the code you will see probably shouldhave named my macro Copy3Back
Relative references can be confusingRelative references can be confusing
So can copying formulasSo can copying formulas
In general, the best use of macro recording is for verysimple repetitive tasks, or for finding out what kind ofcode goes with an action (record macro, then lookat the code)In general, the best use of macro recording is for verysimple repetitive tasks, or for finding out what kind ofcode goes with an action (record macro, then lookat the code)
Next well write our own codeNext well write our own code