1 cs 106 computing fundamentals ii chapter 17 “introduction to vba” herbert g. mayer, psu cs...

41
1 CS 106 Computing Fundamentals II Chapter 17 “Introduction To VBA” Herbert G. Mayer, PSU CS Herbert G. Mayer, PSU CS status 6/30/2013 status 6/30/2013 Initial content copied verbatim from Initial content copied verbatim from CS 106 material developed by CS 106 material developed by CS professors: Cynthia Brown & Robert Martin CS professors: Cynthia Brown & Robert Martin

Upload: annice-morgan

Post on 27-Dec-2015

233 views

Category:

Documents


1 download

TRANSCRIPT

1

CS 106Computing Fundamentals II

Chapter 17“Introduction To VBA”

Herbert G. Mayer, PSU CSHerbert G. Mayer, PSU CSstatus 6/30/2013status 6/30/2013

Initial content copied verbatim fromInitial content copied verbatim fromCS 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: A WarningBut First: A 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 a basic familiarity Assumption: you have a basic familiarity with Excelwith Excel

• If you don’t, or you need a review, you If you don’t, or you need a review, you can get started by going through the can get started by going through the Introduction to Excel in the first moduleIntroduction to Excel in the first module

4

Idea of Objects

• VBA is built on the idea that a workbook VBA is built on the idea that a workbook is a hierarchy of is a hierarchy of objectsobjects

• An object can An object can contain other objectscontain other objects; for ; for example, a workbook contains worksheets, example, a workbook contains worksheets, and the worksheets contain cellsand the worksheets contain cells

• An object can have An object can have propertiesproperties, like the , like the value in a cell or the font used in a cellvalue in a cell or the font used in a cell

• An object can have An object can have methodsmethods, which are , which are actions that affect the objectactions that affect the object

5

Events

• Objects can have events: for example, Objects can have events: for example, opening a workbook is an event; so is opening a workbook is an event; so is clicking on a cellclicking on a cell

• Our Our VBA programs perform tasks when events VBA programs perform tasks when events happenhappen

• The spreadsheet or Excel form we are The spreadsheet or Excel form we are working with will serve as the user working with will serve as the user interface, and events like clicking a interface, and events like clicking a button will trigger the performance of a button will trigger the performance of a tasktask

6

Macros

• VBA programs are called macros. The simplest VBA programs are called macros. The simplest way to get started writing macros is to way to get started writing macros is to record one. This feature lets VBA produce record one. This feature lets VBA produce code based on actions you perform while code based on actions you perform while recordingrecording

• We’ll go through an exampleWe’ll go through an example

• This is not a proper way to create macros This is not a proper way to create macros other than really simple ones, especially if other than really simple ones, especially if formulas are involvedformulas are involved

• It It isis good for getting an idea of what kind good for getting an idea of what kind of code to write to perform a particular task of code to write to perform a particular task

7

BUT FIRST: A Warning!

• Macros can be dangerous! They can change Macros can be dangerous! They can change files on your computer, send emails to files on your computer, send emails to everyone in your address book, and insert everyone in your address book, and insert spyware; hackers love themspyware; hackers love them

• Caveat: Caveat: NEVER run macros from an un-NEVER run macros from an un-trusted sourcetrusted source

• The default setting on the Macro Security The default setting on the Macro Security control (in Windows) is a good one: you control (in Windows) is a good one: you have to authorize macros before you can have to authorize macros before you can run themrun them

8

Here’s the control for the security settings (Windows version)

Macro Security control

9

Get to “Trust Center” Window by clicking the Macro Security control

This default setting is the correct one for us

You will have to check a box to enable macros to run whenever you open a workbook with macros in it.

You will also have to save your workbook as a “Macro-enabled Workbook” with extension .xlsm

10

Macro Security (Mac version)

Get this window by clicking Preferencesunder the Excel menu

11

Be sure that the “warn before opening a filethat contains macros” box is checked

12

Recording a Macro (Windows)

There are two macro recording buttons as shown by the arrows. You can push either one to begin recording.

13

Relative References Control

The “Use Relative References” button lets you choose whether to use relative or absolute references when recording your macro.

The default is to use absolute references.

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 This macro is in the workbook CopyCols.xlsm posted on the websiteCopyCols.xlsm posted on the website

• Using absolute references, we’ll copy one Using absolute references, we’ll copy one column to anothercolumn to another

• The example is shown in Windows; doing it The example is shown in Windows; doing it on the Mac is quite similaron the Mac is quite similar

16

The Worksheet Before We Record

I used R1C1 in Row 1 Col 1 etc. so you can see where data comes from when we copy it.

17

Here’s the screen we get when we push the Record Macro Button

I gave it a descriptivename. If you give it a shortcut key,

make sure it doesn’t conflict with an important one

Be sure todescribe whatit does

Our usualoption

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…

Click herewhen done

[On the Mac, just click the record button againto stop]

20

To run Macro Push Macro Button

Highlight the macro you want to run and push the run button

21

Add a Button to Run the Macro (Windows)

On the developer tab, under Insert, click the little triangle. The icon for a button is at the upper left under Form Controls

22

Add Button to Run the Macro (Mac)

On the Mac, the controls you can addare in the ribbon

23

Click to put Button onto Worksheet

• Put it about where you want it, but you Put it about where you want it, but you can always move it latercan always move it later

• The next step is to associate the button The next step is to associate the button with the macrowith the macro

• The screen on the next page will come up The screen on the next page will come up automaticallyautomatically

24

Highlight Macro Name, Click OK

Before After

25

Click on the button to get a cursor to type meaningful text

26

Final Product

I had to make the button longer to hold the text I wanted

27

Let’s Look at the Code!

Click the Macros button at the upper left of the developer tab and then click the Edit button. This will take you to the VBA Editor.

28

The VBA Window (Windows)

ProjectWindow

PropertiesWindow

Code WindowLet’s just look at the code

for now

29

Code ExplanationSubSub CopyAtoD() CopyAtoD()

''

' CopyAtoD Macro' CopyAtoD Macro

' Copy Column A to Column D' Copy Column A to Column D

''

''

Columns("A:A").SelectColumns("A:A").Select

Selection.CopySelection.Copy

Columns("D:D").SelectColumns("D:D").Select

ActiveSheet.PasteActiveSheet.Paste

End SubEnd Sub

A “Sub” is a working piece of code, a Macro. This is the code for our Macro CopyAtoDA line that starts with a ‘ is a comment. It is not part of the code. VBA used our description for this comment. The editor colors comments green

The End Sub closes off the code for this subroutine. Sub and End Sub are key words for the editor; it colors them blue

30

The Code Body (1)

Columns("A:A").SelectColumns("A:A").Select

Selection.CopySelection.Copy

Columns("D:D").SelectColumns("D:D").Select

ActiveSheet.PasteActiveSheet.Paste

A range of columns (which here is just one column, A) is an object. It has a method Select. This code activates the method to select that column

31

The Code Body (2)

Columns("A:A").SelectColumns("A:A").Select

Selection.CopySelection.Copy

Columns("D:D").SelectColumns("D:D").Select

ActiveSheet.PasteActiveSheet.Paste

A selection is also an object. It has a method called Copy. This line copies the selection (column A) and puts it on the clipboard

32

The Code Body (3)

Columns("A:A").SelectColumns("A:A").Select

Selection.CopySelection.Copy

Columns("D:D").SelectColumns("D:D").Select

ActiveSheet.PasteActiveSheet.Paste

Change the selection from Column A to Column D

33

The Code Body (4)

Columns("A:A").SelectColumns("A:A").Select

Selection.CopySelection.Copy

Columns("D:D").SelectColumns("D:D").Select

ActiveSheet.PasteActiveSheet.Paste Here the sheet is the object when we do a paste. This pastes the information on the clipboard to the selected place on the active worksheet

34

What Is Code?

• The code is a series of instructions to The code is a series of instructions to ExcelExcel

• The instructions are performed in the The instructions are performed in the order given in the code, so order is order given in the code, so order is critically importantcritically important

• The idea of coding is to write The idea of coding is to write instructions to make Excel do what you instructions to make Excel do what you want it to dowant it to do

35

Saving the Workbook: Save as Macro-Enabled Workbook!

36

When you reopen, click the Options button and choose Enable this Content

37

One More Macro

• We’ll do the same macro, but this time We’ll do the same macro, but this time with the Use Relative References option with the Use Relative References option selectedselected

• I’m naming this one “Copy4Back”I’m naming this one “Copy4Back”

• So I will click the relative references So I will click the relative references option, click record macro, and give the option, click record macro, and give the macro a name. Then I will select Column D, macro a name. Then I will select Column D, select Column A, copy Column A to Column select Column A, copy Column A to Column D, and stop recording. Then we make a D, and stop recording. Then we make a button for the new macrobutton for the new macro

38

Here’s what it looks like

39

After Clicking Copy A toD

If I select Column D and click Copy 4 Back, I get the same thing. But if I select Column E and click Copy 4 Back, I get the next picture.(I erased Column D first.)

40

Column B was Copied!

… because I had relative references turned on

41

Slight Problem

• If you look at the code you will see I If you look at the code you will see I probably should have named my macro probably should have named my macro Copy3BackCopy3Back

• Relative references can be confusing Relative references can be confusing

• So can copying formulasSo can copying formulas

• In general, the best use of macro recording In general, the best use of macro recording is for very simple repetitive tasks, or for is for very simple repetitive tasks, or for finding out what kind of code goes with an finding out what kind of code goes with an action (record a macro, then look at the action (record a macro, then look at the code)code)

• Next we’ll write our own codeNext we’ll write our own code