SlideShare a Scribd company logo
1 of 66
Download to read offline
Introduction to VBA
(See Chapters 1 - 4 of Albright)
Kipp Martin
University of Chicago
Booth School of Business
January 4, 2012
1
Excel Files
Files used in this lecture.
I vbIntroClean.xlsm
Outline
Programming Languages
Compilers
Scripting Languages
Motivation for VBA
Brief History
The VB Editor
Object Oriented Programming
Generating Code
Events
3
Programming Languages
Programming languages are used to create applications. For
example, the Microsoft Excel application was written in the C
programming language.
Learning Objectives:
1. Understand the difference between a compiled programming
language and a scripting language.
2. Understand the role of Excel/VBA and MATLAB
3. Understand key tradeoffs
Programming Languages
The following are some popular high-level, languages that have
been used to create applications.
I COBOL (common business-oriented language) An old
language from the 1950s which was designed for accounting
and transaction processing.
I FORTRAN (formula translation) An excellent language for
numerically intensive work.
I C, C++ Good for numerical applications and scientific
computing. It is also used for writing many desktop
applications. C++ is the object oriented version of C.
I Java An extremely popular language for developing Internet
business applications.
I C# A language from Microsoft designed to facilitate the
development of Internet business applications.
Compilers
A programmer writes a set of instructions (source code) that
constitute a program. The source code must get translated into
machine code.
Macintosh
Compiler
Macintosh
Application
Macintosh
Macintosh Source
Code
Windows
Compiler
Windows
Application
Windows Source
Code
Unix
Compiler
Unix
Application
Unix Source Code
Workstation
IBM Compatible
Figure: The compilation process for different operating systems.
6
Compilers
A few key points.
I The executable code created by the compiler is platform
dependent.
I The executable code generated by the compiler cannot be
modified or edited – you must go back to the source code.
I The executable code is binary as opposed to source code
which is text.
I When purchasing software, negotiate to get the source code if
possible.
7
Scripting Languages
An alternative to a compiled language such as C or Java is an
interpreted or scripting language. Two good examples are the
MATLAB scripting language and VBA. What is the difference
between a scripting language and a compiled language?
Figure: A compiled program is a process directly controlled by the OS.
8
Scripting Languages
A scripting language need an interpreter or host.
Figure: A interpreted program is a process directly controlled by host
which in turn is controlled by the OS.
9
Scripting Languages
Scripting languages are easier than compiled languages.
I A compiled programming language generally has a much
larger vocabulary/syntax to learn than a scripted language.
There is more to learn.
I A compiled programming language is usually conceptually
more difficult than a scripted language. Concepts of such as
pointers, polymorphism, virtual classes, templating etc. are
nontrivial to learn.
I There is a bigger burden placed on the programmer using a
compiled language. For example, garbage collection or
allocating memory when it is needed.
I A compiled language is often more “rigid.” This rigidity has
its advantages, but also slows coding down.
Scripting Languages
Scripting languages give “instant gratification.”
>> x = 10;
>> y = 0;
>> x/y;
MATLAB will immediately come back with the message “Warning:
Divide by zero.” MATLAB is “interpreting” the commands as you
type them in.
With a compiled language you must compile and link the entire
problem and then run it in order to discover the problem. The
compilation and linking phase can be very time consuming. You
get feedback much faster with the scripting language.
Scripting Languages
Downside: a scripting application will not run as fast as a
compiled application. The scripting language application is running
inside the host which is running inside the operating system. When
should you use a scripting language? More later!
Example scripting languages:
1. Javascript – this scripting language is very popular and is
used to add functionality to a browser. Browsers such as
Internet Explorer or Firefox serve as the interpreter/host for
for Javascript.
2. Visual Basic for Applications (VBA) – this scripting
language is immensely popular in the Microsoft world. It is
used to add functionality to the suite of Office products. Each
Office product such as Excel or Word serves as the host.
3. The MATLAB scripting language and the MATLAB
program is the host.
4. Python and an interpreter
Scripting Languages
Scripting languages make for easy programming.
However, there are tradeoffs!
A program written in Excel VBA or MATLAB script will not
execute as fast as code written in C. There is a performance hit for
VBA and MATLAB.
Key Idea: YOU must make a decision regarding the tradeoff
between execution time and development time.
Computers have become so fast in recent years that execution time
is becoming less relevant. Hence, software such as MATLAB and
Excel/VBA that can shorten the development cycle have become
more important.
Scripting Languages
Development versus execution time.
Development Time
Execution
Time
Slow machine
Fast machine
Figure: Development versus execution time.
14
Scripting Languages
Other things that are desirable but may slow down either execution
or development time include the following.
1. extensive error checking (will slow both development and
execution time)
2. putting in extensive documentation (will slow development
time, but have no effect on execution time)
3. Using object oriented programming, making extensive uses of
classes and polymorphism (will speed development time but
slow execution time).
15
Scripting Languages
On another note:
A person in the software industry recently remarked to me that she
thought that not all of the decline in jobs for “real programmers”
was due to overseas outsourcing. Rather, she felt that because of
the proliferation of easy to scripting languages many managers
were actually doing programming and they didn’t need real
programmers to deal with third generation languages.
Tradeoffs – Why VBA?
Excel competitors:
I MATLAB, Mathematica
I SAS, R
I Python, Perl
Among the scripting languages, why use VBA?
Think about Willie Sutton for an analogy?
Tradeoffs – Why VBA?
VBA is both powerful and flexible.
I Build models easily – take input parameters and generate a
model instance.
I Provide a user interface/GUI so the user doesn’t have to do a
lot of work.
I Automate tasks through Macros.
I Connect to other programs/applications, e.g. a SQL Server or
Access database.
I Excel with VBA is an IDE – Integrated Development
Environment
18
Tradeoffs – Why VBA?
Excel with VBA is an IDE. Key features include:
I There is a VBA editor. This is used for entering VB code.
I There is a generic “UserForm” for creating user interfaces.
I There a huge function library to select from. You can also
write your own functions using VBA.
I Excel can be used for statistical analysis. There are routines
for calculating means, variances, correlations, running
regressions, forecasting models, etc.
Tradeoffs – Why VBA?
Key features (continued):
I You can use Excel for mathematical optimization. We will
discuss the GAMS package later in the quarter.
I You can use Excel for simulation.
I Excel is excellent for creating graphs and histograms.
I Excel can import and export data in various formats. It can
even read and write XML.
I Excel can serve as a database. You can filter and query the
data.
I You can interface with other programs using Web services.
Tradeoffs – Why VBA?
VBA, MATLAB, Python – does it really matter which one you
learn?
No!!! You will learn concepts.
I am a former Booth student, and took your VBA/MAtlab
class last winter. I just had a job interview that
requires the use of Python ...
it didnt sound like the tasks they required
were that extensive....
Is Python that different from anything we used in class?
Thanks in advance for any help you can give....
And if I hadn’t taken your class I wouldn’t even
be in the running so thanks for offering it!
Brief History
The first spreadsheet program for the PC was VisiCal. Created by
Dan Bricklin (Harvard MBA student) and his buddy Bob
Frankston in 1978. Product was sold and marketed by Dan
Fylstra’s (another Harvard MBA) company VisiCorp. It was
developed for the Apple II. First “killer app” for the PC.
Lotus 1-2-3 was the first big commercial success.
I a spreadsheet
I a graphics package
I a database
Microsoft Excel is now the major player in this market.
Brief History
Microsoft’s first product was a very elementary Basic compiler.
Then Microsoft created a widely successful product called Visual
Basic.
Then Microsoft, in an extremely rare and unusual moment of
innovative clarity, combined Visual Basic with Microsoft Office
resulting in VBA (Visual Basic for Applications).
23
VB Flavors
I VB now VB .NET – a programming language that can be
compiled into an application. Part of the Microsoft Visual
Studio IDE
I VBA – a scripting language that uses one of the Office
products, e.g. Excel, Word, Power Point, Access as the host.
We will use VBA for Excel.
I VBScript – the browser, IE Explorer, is the host. Designed to
compete with the Netscape Java Script.
The VB Editor
25
The VB Editor
In order to access the VB editor (Excel 2007)
I Click on the Developer Tab in Excel ribbon
I Click on Visual Basic to bring up the Editor.
If you do not see the Developer Tap click on the Office Button in
the upper left-hand corner. Then select Excel Options at the
bottom of the window. Make sure ”Show Developer tab in the
Ribbon” is selected.
The VB Editor
Bringing up the Developer Tab
27
The VB Editor
Code Window
Properties Window
Project Explorer
28
The VB Editor
The VB Editor is a set of Windows. You can get a list of available
Windows by selecting the View menu item in the VB editor.
I The Project Explorer: sort of like the Windows Explorer
and allows to explore the files structure of the files in your
project.
I Projects
I Objects – the top level objects such as the Workbook and
Worksheets
I User Forms – GUIs
I Modules – chunks of code that can be executed across
worksheets, not necessarily specific to a worksheet.
The VB Editor
I The Code Window: this is a text editor. You type VBA code
in the Code Window. You will spend a lot of time in this
Window.
I The Properties Window: This will be used later, when we
build GUIs. Ignore it for now (although nice if you want to
change a module name)
The VB Editor
Components of the VB Editor (continued)
I The Immediate Window Where you go for instant
gratification.
Y = 4/5
?Y
0.8
?Worksheets("Sheet1").Range("amatrix").address
$C$5:$D$8
Y=2/3
?Y
0.66666666666666
Also used for debugging as we see later.
I The Watch Window Not now – later, this is good for
debugging
The VB Editor
The VBA editor also contains a set of Toolbars. Again, go to the
menu item View and select Toolbars.
I Standard Toolbar (play around with the various options)
I Edit Toolbar (play around with the various options)
I Debug Toolbar (later)
I UserForm (later)
Go over Chapter 3 in the text several times.
Object Oriented Programming
Modern programming languages such as C++ and Java are object
oriented. Even scripting languages such as VBA have object
oriented features.
KEY IDEA: develop reusable software modules called objects and
make it easy to modify or extend the objects for use in different
applications.
Object-oriented programming is built around the concepts of a
class and an object. A class is an abstraction of a real-world object
and describes the essence of the object. For example the concept
of a worksheet is a class. A specific worksheet with data is an
object in the class.
A class is usually composed of 1) properties (often called primitives
or data members) and 2) methods (often called functions) that
operate on the data. In object speak we say the properties and
methods are encapsulated into objects.
33
Object Oriented Programming
Each of the Microsoft Office family members (Excel, Access, etc.)
support VBA.
The key difference between the various flavors of VBA is the object
model.
The Excel VBA object model naturally focuses on the concepts of
a Workbook, Worksheet, and Range.
What might be some reasonable key objects in Word VBA? For
example, kind of object might correspond to a Workbook?
34
Object Oriented Programming
The two KEY IDEAS for the first part of this course:
I The concept of an object
I How to work with the range object (next week)
35
Object Oriented Programming
A fantastic learning aid is the object browser. Spend time with
this! The object browser is useful for rookies and experienced
veterans alike.
36
Object Oriented Programming
In the left-most Classes window scroll down and observe the
various classes.
Select the Worksheet class.
In the right window you will see Members of Worksheet. Notice
the three different icon types each denoting a different type of
member
I Properties Member – icons with a hand
I Sub Member – green icon
I Event Member – lighting bolt icon
37
Object Oriented Programming
Select the Worksheet class. The Range member is a property of
the Worksheet class. The Range is also a class. A class can have
a member property that is also a class. Neat!
38
Object Oriented Programming
Key Idea: Class hierarchy
The Workbook class has Worksheet class members.
The Worksheet class has Range class members.
The Range class has Font class members.
The Font class has Size data member (an Variant).
Object Oriented Programming
The SaveAs member is a sub (I like to call these methods) of the
Worksheet class.
40
Object Oriented Programming
The SaveAs method has arguments. The arguments tell the
method how to act. Some arguments are required some are
optional [].
Sub SaveAs(Filename As String,
[FileFormat],
[Password],
[WriteResPassword],
[ReadOnlyRecommended],
[CreateBackup],
[AddToMru],
[TextCodepage],
[TextVisualLayout],
[Local])
Object Oriented Programming
The following code illustrates the object oriented nature of VBA.
Sub DemoObject()
Dim ws As Worksheet
Dim rng As Range
Set ws = Worksheets("DemoObject")
’A method with no arguments
ws.Activate
ws.Range("A1") = 99
Set rng = ws.Range("A1")
rng.Font.Italic = True
’Set the value of a property
ws.Range("A1").Font.Size = 22
’Methods with arguments
rng.Copy Destination:=Range("G1")
End Sub
Object Oriented Programming: “Dot
Notation”
Member Specifiction: The notation to specify a member of an
object is
Object.Member
For example, rng.Font
or, rng.Calcuate
A class member can be a class that has other members. For
example: rng.Font.Italic
To set the value of a class member that is a property do the
following
rng.Font.Italic = True
43
Object Oriented Programming: Method
Specification
Method Specifiction: The notation to specify a method of an
object for methods with no arguments is
Object.Method
For example, ws.Activate
If the method has arguments the notation is
Object.Method Arg1:=Arg1Value, Arg2:=Arg2Value, ..
For example: rng.Copy Destination:=Range(”G1”)
44
Object Oriented Programming: Method
Specification
Another way to specify is to drop the argument name, i.e.
Object.Method Arg1Value, Arg2Value, ..
rng.Copy Range(”G1”)
or, when used in an assignment parenthesis
Dim money as Currency
money = VBA.Format(34.124545, "Currency")
45
Object Oriented Psrogramming
Intellisense: wow is this great, or what!
In the code window type in:
Class (object) and all of the members associated the class (object)
will pop up in alphabetical order
If you type in the name of the method, Intellisense will list the
arguments needed, e.g. type
MsgBox and hit the space, the arguments to MsgBox will pop up.
46
Object Oriented Programming
KEY CONCEPTS:
I Class
I Object
I Class Members – the members define the class (properties and
methods/procedures)
I Method ( also called subroutines, procedures, or functions)
I Property – data describing the class
I Arguments – inputs to a method/function
Generating Code
There are three basic ways to generate code:
I Import code from a file
I Enter code by hand into the code window
I Create a macro
48
Import Code
Open an Excel file that has VBA code and select the Visual Basic
Icon in the Developer tab. You will see the code in in the VB
editor.
Important – Under Macro Security you will need to check the box
for Trust Access to the VBA project model.
49
Generating Code
There are two ways to generate new code. Either type the code
into the Code Window by hand or record a Macro. For now we
focus on recording macros.
Macro – a recording of key strokes and mouse clicks
50
Macros
After clicking on the record button, the figure below appears.
Name the macro and click OK to start recording.
When you are done recording your mouse clicks, click Stop
Recording icon.
51
Macros
We can also make a macro available to all workbooks.
52
Macros
I Download the file vbIntro.xls and select the copyMacro
worksheet.
I Turn on Macro Recording
I Name the macro copyMacro
I Highlight the data for ages 30 through 40
I Take the “cross” in the lower left hand side and copy through
the age of 60.
I Copy cntrl-C
I Select Cell D2
I Paste cntrl-V
I Select cell A1
I Stop Recording
Macros
Now go into the VB editor and examine the code. You should have:
Sub copyMacro()
’
’ copyMacro Macro
’
’
Range("A2:A12").Select
Selection.AutoFill Destination:=Range("A2:A32"), _
Type:=xlFillDefault
Range("A2:A32").Select
Selection.Copy
Range("D2").Select
ActiveSheet.Paste
Range("A1").Select
End Sub
Macros
1. What is Range? (Object, method, property)
2. What is Select? (Object, method, property)
3. What is Selection? (Object, method, property)
4. What is AutoFill? (Object, method, property)
5. What are the arguments for AutoFill?
6. What are the arguments for Paste
Macros
I A macro corresponds to code in a module. In particular the
macro is a procedure.
I The default Module is Module1 – you can change this name
in the Properties Window.
I A module is code “seen” by all of the spreadsheets.
I The name of the procedure corresponds to the name of the
macro.
I Comments are preceded in VB by a single quote.
I We can continue code from one line to the next using an
(underscore)
56
Macros
SUMMARY
A sub procedure has the format:
Sub SubName()
... VBA Code ...
End Sub
57
Macros
Download the file vbIntro.xls and select the flightMacro
worksheet.
First understand filtering and sorting.
Highlight the entire flight data table.
Make sure the Home tab is selected. Then in the ribbon Select
Data>Filter
Play around and do some sorting and filtering
Now deselect Filter so we are back to the original worksheet.
58
Macros
59
Macros
GENERATING FILTERING MACROS
I Step 1: Deselect Filter so we are back to the original
worksheet.
I Step 2: Start recording a macro named
ViewHongKongFlights
I Step 3: Highlight the range A3:D15.
I Step 4: Select Data>Filter
I Step 5: In the Destination column select Hong Kong
I Step 6: Select cell A1
I Step 7: Stop Recording
Macros
GENERATING FILTERING MACROS
Your code should look like:
Sub ViewHongKongFlights()
Range("A3:D15").Select
Selection.AutoFilter
Selection.AutoFilter Field:=1, Criteria1:="Hong Kong"
Range("A1").Select
End Sub
Edit the ViewHongKongFlights() Sub Procedure so that Beijing
flights are viewed instead of Hong Kong flights.
Macros
CODE GENERATION
Do the following:
I Based on your understanding of VB create a procedure
(without recording a macro) called ViewEconomy that will
show all of the available Economy flights.
I Test and run these macros
Events
Events: actions that take place in the Excel window that are
linked to code (often called handlers).
I Open a workbook
I Click on a command button
I Activate a worksheet
An event procedure is a procedure except that it is associated
with an excel event.
Events
64
Events
Event Example: the Command Button object.
See Developer and Insert
Click on the Command Button object and then click somewhere on
the spreadsheet.
Click on New
Create the following code:
Sub Button1_Click()
MsgBox "Hello World"
End Sub
65
Events
Review: An object is made up of?
66

More Related Content

Similar to vbaintro.pdf

Specification Of The Programming Language Of Java
Specification Of The Programming Language Of JavaSpecification Of The Programming Language Of Java
Specification Of The Programming Language Of JavaKim Moore
 
Concept of computer programming iv
Concept of computer programming ivConcept of computer programming iv
Concept of computer programming ivEyelean xilef
 
The Ring programming language version 1.5.3 book - Part 5 of 184
The Ring programming language version 1.5.3 book - Part 5 of 184The Ring programming language version 1.5.3 book - Part 5 of 184
The Ring programming language version 1.5.3 book - Part 5 of 184Mahmoud Samir Fayed
 
The Ring programming language version 1.5.2 book - Part 5 of 181
The Ring programming language version 1.5.2 book - Part 5 of 181The Ring programming language version 1.5.2 book - Part 5 of 181
The Ring programming language version 1.5.2 book - Part 5 of 181Mahmoud Samir Fayed
 
The Ring programming language version 1.5.4 book - Part 5 of 185
The Ring programming language version 1.5.4 book - Part 5 of 185The Ring programming language version 1.5.4 book - Part 5 of 185
The Ring programming language version 1.5.4 book - Part 5 of 185Mahmoud Samir Fayed
 
Oop lecture1-chapter1(review of java)
Oop lecture1-chapter1(review of java)Oop lecture1-chapter1(review of java)
Oop lecture1-chapter1(review of java)Dastan Kamaran
 
Oop lecture1-chapter1(review of java)
Oop lecture1-chapter1(review of java)Oop lecture1-chapter1(review of java)
Oop lecture1-chapter1(review of java)Dastan Kamaran
 
Programming lesson1
Programming lesson1Programming lesson1
Programming lesson1camfollower
 
What is the best programming language to learn if you want to work on the blo...
What is the best programming language to learn if you want to work on the blo...What is the best programming language to learn if you want to work on the blo...
What is the best programming language to learn if you want to work on the blo...BlockchainX
 
The Ring programming language version 1.6 book - Part 6 of 189
The Ring programming language version 1.6 book - Part 6 of 189The Ring programming language version 1.6 book - Part 6 of 189
The Ring programming language version 1.6 book - Part 6 of 189Mahmoud Samir Fayed
 
ICT-DBA4 -05-0811-Apply-Object-Oriented-Programming-Language-Skills.doc
ICT-DBA4 -05-0811-Apply-Object-Oriented-Programming-Language-Skills.docICT-DBA4 -05-0811-Apply-Object-Oriented-Programming-Language-Skills.doc
ICT-DBA4 -05-0811-Apply-Object-Oriented-Programming-Language-Skills.docAmanGunner
 
Week 3 Lecture 1 - Business SoftwareManagement of Information .docx
Week 3 Lecture 1 - Business SoftwareManagement of Information .docxWeek 3 Lecture 1 - Business SoftwareManagement of Information .docx
Week 3 Lecture 1 - Business SoftwareManagement of Information .docxjessiehampson
 
VSTO + LOB Apps
VSTO + LOB AppsVSTO + LOB Apps
VSTO + LOB AppsJoao Livio
 
Java As A Programming Language
Java As A Programming LanguageJava As A Programming Language
Java As A Programming LanguageJennifer Wright
 
Presentation of programming languages for beginners
Presentation of programming languages for beginnersPresentation of programming languages for beginners
Presentation of programming languages for beginnersClement Levallois
 
A Research Study of Data Collection and Analysis of Semantics of Programming ...
A Research Study of Data Collection and Analysis of Semantics of Programming ...A Research Study of Data Collection and Analysis of Semantics of Programming ...
A Research Study of Data Collection and Analysis of Semantics of Programming ...IRJET Journal
 
Trend of Visual Programming Language
Trend of Visual Programming LanguageTrend of Visual Programming Language
Trend of Visual Programming LanguageTeddy Marcus
 

Similar to vbaintro.pdf (20)

Specification Of The Programming Language Of Java
Specification Of The Programming Language Of JavaSpecification Of The Programming Language Of Java
Specification Of The Programming Language Of Java
 
Concept of computer programming iv
Concept of computer programming ivConcept of computer programming iv
Concept of computer programming iv
 
The Ring programming language version 1.5.3 book - Part 5 of 184
The Ring programming language version 1.5.3 book - Part 5 of 184The Ring programming language version 1.5.3 book - Part 5 of 184
The Ring programming language version 1.5.3 book - Part 5 of 184
 
The Ring programming language version 1.5.2 book - Part 5 of 181
The Ring programming language version 1.5.2 book - Part 5 of 181The Ring programming language version 1.5.2 book - Part 5 of 181
The Ring programming language version 1.5.2 book - Part 5 of 181
 
The Ring programming language version 1.5.4 book - Part 5 of 185
The Ring programming language version 1.5.4 book - Part 5 of 185The Ring programming language version 1.5.4 book - Part 5 of 185
The Ring programming language version 1.5.4 book - Part 5 of 185
 
Oop lecture1-chapter1(review of java)
Oop lecture1-chapter1(review of java)Oop lecture1-chapter1(review of java)
Oop lecture1-chapter1(review of java)
 
Oop lecture1-chapter1(review of java)
Oop lecture1-chapter1(review of java)Oop lecture1-chapter1(review of java)
Oop lecture1-chapter1(review of java)
 
Code learning
Code learningCode learning
Code learning
 
Programming lesson1
Programming lesson1Programming lesson1
Programming lesson1
 
What is the best programming language to learn if you want to work on the blo...
What is the best programming language to learn if you want to work on the blo...What is the best programming language to learn if you want to work on the blo...
What is the best programming language to learn if you want to work on the blo...
 
The Ring programming language version 1.6 book - Part 6 of 189
The Ring programming language version 1.6 book - Part 6 of 189The Ring programming language version 1.6 book - Part 6 of 189
The Ring programming language version 1.6 book - Part 6 of 189
 
ICT-DBA4 -05-0811-Apply-Object-Oriented-Programming-Language-Skills.doc
ICT-DBA4 -05-0811-Apply-Object-Oriented-Programming-Language-Skills.docICT-DBA4 -05-0811-Apply-Object-Oriented-Programming-Language-Skills.doc
ICT-DBA4 -05-0811-Apply-Object-Oriented-Programming-Language-Skills.doc
 
Programming language
Programming languageProgramming language
Programming language
 
Week 3 Lecture 1 - Business SoftwareManagement of Information .docx
Week 3 Lecture 1 - Business SoftwareManagement of Information .docxWeek 3 Lecture 1 - Business SoftwareManagement of Information .docx
Week 3 Lecture 1 - Business SoftwareManagement of Information .docx
 
VSTO + LOB Apps
VSTO + LOB AppsVSTO + LOB Apps
VSTO + LOB Apps
 
Java As A Programming Language
Java As A Programming LanguageJava As A Programming Language
Java As A Programming Language
 
Presentation of programming languages for beginners
Presentation of programming languages for beginnersPresentation of programming languages for beginners
Presentation of programming languages for beginners
 
A Research Study of Data Collection and Analysis of Semantics of Programming ...
A Research Study of Data Collection and Analysis of Semantics of Programming ...A Research Study of Data Collection and Analysis of Semantics of Programming ...
A Research Study of Data Collection and Analysis of Semantics of Programming ...
 
Trend of Visual Programming Language
Trend of Visual Programming LanguageTrend of Visual Programming Language
Trend of Visual Programming Language
 
miniproject.pptx
miniproject.pptxminiproject.pptx
miniproject.pptx
 

Recently uploaded

The CMO Survey - Highlights and Insights Report - Spring 2024
The CMO Survey - Highlights and Insights Report - Spring 2024The CMO Survey - Highlights and Insights Report - Spring 2024
The CMO Survey - Highlights and Insights Report - Spring 2024christinemoorman
 
Youth Involvement in an Innovative Coconut Value Chain by Mwalimu Menza
Youth Involvement in an Innovative Coconut Value Chain by Mwalimu MenzaYouth Involvement in an Innovative Coconut Value Chain by Mwalimu Menza
Youth Involvement in an Innovative Coconut Value Chain by Mwalimu Menzaictsugar
 
BEST Call Girls In Old Faridabad ✨ 9773824855 ✨ Escorts Service In Delhi Ncr,
BEST Call Girls In Old Faridabad ✨ 9773824855 ✨ Escorts Service In Delhi Ncr,BEST Call Girls In Old Faridabad ✨ 9773824855 ✨ Escorts Service In Delhi Ncr,
BEST Call Girls In Old Faridabad ✨ 9773824855 ✨ Escorts Service In Delhi Ncr,noida100girls
 
FULL ENJOY Call girls in Paharganj Delhi | 8377087607
FULL ENJOY Call girls in Paharganj Delhi | 8377087607FULL ENJOY Call girls in Paharganj Delhi | 8377087607
FULL ENJOY Call girls in Paharganj Delhi | 8377087607dollysharma2066
 
Lowrate Call Girls In Sector 18 Noida ❤️8860477959 Escorts 100% Genuine Servi...
Lowrate Call Girls In Sector 18 Noida ❤️8860477959 Escorts 100% Genuine Servi...Lowrate Call Girls In Sector 18 Noida ❤️8860477959 Escorts 100% Genuine Servi...
Lowrate Call Girls In Sector 18 Noida ❤️8860477959 Escorts 100% Genuine Servi...lizamodels9
 
India Consumer 2024 Redacted Sample Report
India Consumer 2024 Redacted Sample ReportIndia Consumer 2024 Redacted Sample Report
India Consumer 2024 Redacted Sample ReportMintel Group
 
Buy gmail accounts.pdf Buy Old Gmail Accounts
Buy gmail accounts.pdf Buy Old Gmail AccountsBuy gmail accounts.pdf Buy Old Gmail Accounts
Buy gmail accounts.pdf Buy Old Gmail AccountsBuy Verified Accounts
 
Call Girls Miyapur 7001305949 all area service COD available Any Time
Call Girls Miyapur 7001305949 all area service COD available Any TimeCall Girls Miyapur 7001305949 all area service COD available Any Time
Call Girls Miyapur 7001305949 all area service COD available Any Timedelhimodelshub1
 
8447779800, Low rate Call girls in Kotla Mubarakpur Delhi NCR
8447779800, Low rate Call girls in Kotla Mubarakpur Delhi NCR8447779800, Low rate Call girls in Kotla Mubarakpur Delhi NCR
8447779800, Low rate Call girls in Kotla Mubarakpur Delhi NCRashishs7044
 
Global Scenario On Sustainable and Resilient Coconut Industry by Dr. Jelfina...
Global Scenario On Sustainable  and Resilient Coconut Industry by Dr. Jelfina...Global Scenario On Sustainable  and Resilient Coconut Industry by Dr. Jelfina...
Global Scenario On Sustainable and Resilient Coconut Industry by Dr. Jelfina...ictsugar
 
Intro to BCG's Carbon Emissions Benchmark_vF.pdf
Intro to BCG's Carbon Emissions Benchmark_vF.pdfIntro to BCG's Carbon Emissions Benchmark_vF.pdf
Intro to BCG's Carbon Emissions Benchmark_vF.pdfpollardmorgan
 
Independent Call Girls Andheri Nightlaila 9967584737
Independent Call Girls Andheri Nightlaila 9967584737Independent Call Girls Andheri Nightlaila 9967584737
Independent Call Girls Andheri Nightlaila 9967584737Riya Pathan
 
8447779800, Low rate Call girls in Saket Delhi NCR
8447779800, Low rate Call girls in Saket Delhi NCR8447779800, Low rate Call girls in Saket Delhi NCR
8447779800, Low rate Call girls in Saket Delhi NCRashishs7044
 
Call Girls In Sikandarpur Gurgaon ❤️8860477959_Russian 100% Genuine Escorts I...
Call Girls In Sikandarpur Gurgaon ❤️8860477959_Russian 100% Genuine Escorts I...Call Girls In Sikandarpur Gurgaon ❤️8860477959_Russian 100% Genuine Escorts I...
Call Girls In Sikandarpur Gurgaon ❤️8860477959_Russian 100% Genuine Escorts I...lizamodels9
 
Call Girls In Sikandarpur Gurgaon ❤️8860477959_Russian 100% Genuine Escorts I...
Call Girls In Sikandarpur Gurgaon ❤️8860477959_Russian 100% Genuine Escorts I...Call Girls In Sikandarpur Gurgaon ❤️8860477959_Russian 100% Genuine Escorts I...
Call Girls In Sikandarpur Gurgaon ❤️8860477959_Russian 100% Genuine Escorts I...lizamodels9
 
2024 Numerator Consumer Study of Cannabis Usage
2024 Numerator Consumer Study of Cannabis Usage2024 Numerator Consumer Study of Cannabis Usage
2024 Numerator Consumer Study of Cannabis UsageNeil Kimberley
 
8447779800, Low rate Call girls in Tughlakabad Delhi NCR
8447779800, Low rate Call girls in Tughlakabad Delhi NCR8447779800, Low rate Call girls in Tughlakabad Delhi NCR
8447779800, Low rate Call girls in Tughlakabad Delhi NCRashishs7044
 
Contemporary Economic Issues Facing the Filipino Entrepreneur (1).pptx
Contemporary Economic Issues Facing the Filipino Entrepreneur (1).pptxContemporary Economic Issues Facing the Filipino Entrepreneur (1).pptx
Contemporary Economic Issues Facing the Filipino Entrepreneur (1).pptxMarkAnthonyAurellano
 
Investment in The Coconut Industry by Nancy Cheruiyot
Investment in The Coconut Industry by Nancy CheruiyotInvestment in The Coconut Industry by Nancy Cheruiyot
Investment in The Coconut Industry by Nancy Cheruiyotictsugar
 
Call US-88OO1O2216 Call Girls In Mahipalpur Female Escort Service
Call US-88OO1O2216 Call Girls In Mahipalpur Female Escort ServiceCall US-88OO1O2216 Call Girls In Mahipalpur Female Escort Service
Call US-88OO1O2216 Call Girls In Mahipalpur Female Escort Servicecallgirls2057
 

Recently uploaded (20)

The CMO Survey - Highlights and Insights Report - Spring 2024
The CMO Survey - Highlights and Insights Report - Spring 2024The CMO Survey - Highlights and Insights Report - Spring 2024
The CMO Survey - Highlights and Insights Report - Spring 2024
 
Youth Involvement in an Innovative Coconut Value Chain by Mwalimu Menza
Youth Involvement in an Innovative Coconut Value Chain by Mwalimu MenzaYouth Involvement in an Innovative Coconut Value Chain by Mwalimu Menza
Youth Involvement in an Innovative Coconut Value Chain by Mwalimu Menza
 
BEST Call Girls In Old Faridabad ✨ 9773824855 ✨ Escorts Service In Delhi Ncr,
BEST Call Girls In Old Faridabad ✨ 9773824855 ✨ Escorts Service In Delhi Ncr,BEST Call Girls In Old Faridabad ✨ 9773824855 ✨ Escorts Service In Delhi Ncr,
BEST Call Girls In Old Faridabad ✨ 9773824855 ✨ Escorts Service In Delhi Ncr,
 
FULL ENJOY Call girls in Paharganj Delhi | 8377087607
FULL ENJOY Call girls in Paharganj Delhi | 8377087607FULL ENJOY Call girls in Paharganj Delhi | 8377087607
FULL ENJOY Call girls in Paharganj Delhi | 8377087607
 
Lowrate Call Girls In Sector 18 Noida ❤️8860477959 Escorts 100% Genuine Servi...
Lowrate Call Girls In Sector 18 Noida ❤️8860477959 Escorts 100% Genuine Servi...Lowrate Call Girls In Sector 18 Noida ❤️8860477959 Escorts 100% Genuine Servi...
Lowrate Call Girls In Sector 18 Noida ❤️8860477959 Escorts 100% Genuine Servi...
 
India Consumer 2024 Redacted Sample Report
India Consumer 2024 Redacted Sample ReportIndia Consumer 2024 Redacted Sample Report
India Consumer 2024 Redacted Sample Report
 
Buy gmail accounts.pdf Buy Old Gmail Accounts
Buy gmail accounts.pdf Buy Old Gmail AccountsBuy gmail accounts.pdf Buy Old Gmail Accounts
Buy gmail accounts.pdf Buy Old Gmail Accounts
 
Call Girls Miyapur 7001305949 all area service COD available Any Time
Call Girls Miyapur 7001305949 all area service COD available Any TimeCall Girls Miyapur 7001305949 all area service COD available Any Time
Call Girls Miyapur 7001305949 all area service COD available Any Time
 
8447779800, Low rate Call girls in Kotla Mubarakpur Delhi NCR
8447779800, Low rate Call girls in Kotla Mubarakpur Delhi NCR8447779800, Low rate Call girls in Kotla Mubarakpur Delhi NCR
8447779800, Low rate Call girls in Kotla Mubarakpur Delhi NCR
 
Global Scenario On Sustainable and Resilient Coconut Industry by Dr. Jelfina...
Global Scenario On Sustainable  and Resilient Coconut Industry by Dr. Jelfina...Global Scenario On Sustainable  and Resilient Coconut Industry by Dr. Jelfina...
Global Scenario On Sustainable and Resilient Coconut Industry by Dr. Jelfina...
 
Intro to BCG's Carbon Emissions Benchmark_vF.pdf
Intro to BCG's Carbon Emissions Benchmark_vF.pdfIntro to BCG's Carbon Emissions Benchmark_vF.pdf
Intro to BCG's Carbon Emissions Benchmark_vF.pdf
 
Independent Call Girls Andheri Nightlaila 9967584737
Independent Call Girls Andheri Nightlaila 9967584737Independent Call Girls Andheri Nightlaila 9967584737
Independent Call Girls Andheri Nightlaila 9967584737
 
8447779800, Low rate Call girls in Saket Delhi NCR
8447779800, Low rate Call girls in Saket Delhi NCR8447779800, Low rate Call girls in Saket Delhi NCR
8447779800, Low rate Call girls in Saket Delhi NCR
 
Call Girls In Sikandarpur Gurgaon ❤️8860477959_Russian 100% Genuine Escorts I...
Call Girls In Sikandarpur Gurgaon ❤️8860477959_Russian 100% Genuine Escorts I...Call Girls In Sikandarpur Gurgaon ❤️8860477959_Russian 100% Genuine Escorts I...
Call Girls In Sikandarpur Gurgaon ❤️8860477959_Russian 100% Genuine Escorts I...
 
Call Girls In Sikandarpur Gurgaon ❤️8860477959_Russian 100% Genuine Escorts I...
Call Girls In Sikandarpur Gurgaon ❤️8860477959_Russian 100% Genuine Escorts I...Call Girls In Sikandarpur Gurgaon ❤️8860477959_Russian 100% Genuine Escorts I...
Call Girls In Sikandarpur Gurgaon ❤️8860477959_Russian 100% Genuine Escorts I...
 
2024 Numerator Consumer Study of Cannabis Usage
2024 Numerator Consumer Study of Cannabis Usage2024 Numerator Consumer Study of Cannabis Usage
2024 Numerator Consumer Study of Cannabis Usage
 
8447779800, Low rate Call girls in Tughlakabad Delhi NCR
8447779800, Low rate Call girls in Tughlakabad Delhi NCR8447779800, Low rate Call girls in Tughlakabad Delhi NCR
8447779800, Low rate Call girls in Tughlakabad Delhi NCR
 
Contemporary Economic Issues Facing the Filipino Entrepreneur (1).pptx
Contemporary Economic Issues Facing the Filipino Entrepreneur (1).pptxContemporary Economic Issues Facing the Filipino Entrepreneur (1).pptx
Contemporary Economic Issues Facing the Filipino Entrepreneur (1).pptx
 
Investment in The Coconut Industry by Nancy Cheruiyot
Investment in The Coconut Industry by Nancy CheruiyotInvestment in The Coconut Industry by Nancy Cheruiyot
Investment in The Coconut Industry by Nancy Cheruiyot
 
Call US-88OO1O2216 Call Girls In Mahipalpur Female Escort Service
Call US-88OO1O2216 Call Girls In Mahipalpur Female Escort ServiceCall US-88OO1O2216 Call Girls In Mahipalpur Female Escort Service
Call US-88OO1O2216 Call Girls In Mahipalpur Female Escort Service
 

vbaintro.pdf

  • 1. Introduction to VBA (See Chapters 1 - 4 of Albright) Kipp Martin University of Chicago Booth School of Business January 4, 2012 1
  • 2. Excel Files Files used in this lecture. I vbIntroClean.xlsm
  • 3. Outline Programming Languages Compilers Scripting Languages Motivation for VBA Brief History The VB Editor Object Oriented Programming Generating Code Events 3
  • 4. Programming Languages Programming languages are used to create applications. For example, the Microsoft Excel application was written in the C programming language. Learning Objectives: 1. Understand the difference between a compiled programming language and a scripting language. 2. Understand the role of Excel/VBA and MATLAB 3. Understand key tradeoffs
  • 5. Programming Languages The following are some popular high-level, languages that have been used to create applications. I COBOL (common business-oriented language) An old language from the 1950s which was designed for accounting and transaction processing. I FORTRAN (formula translation) An excellent language for numerically intensive work. I C, C++ Good for numerical applications and scientific computing. It is also used for writing many desktop applications. C++ is the object oriented version of C. I Java An extremely popular language for developing Internet business applications. I C# A language from Microsoft designed to facilitate the development of Internet business applications.
  • 6. Compilers A programmer writes a set of instructions (source code) that constitute a program. The source code must get translated into machine code. Macintosh Compiler Macintosh Application Macintosh Macintosh Source Code Windows Compiler Windows Application Windows Source Code Unix Compiler Unix Application Unix Source Code Workstation IBM Compatible Figure: The compilation process for different operating systems. 6
  • 7. Compilers A few key points. I The executable code created by the compiler is platform dependent. I The executable code generated by the compiler cannot be modified or edited – you must go back to the source code. I The executable code is binary as opposed to source code which is text. I When purchasing software, negotiate to get the source code if possible. 7
  • 8. Scripting Languages An alternative to a compiled language such as C or Java is an interpreted or scripting language. Two good examples are the MATLAB scripting language and VBA. What is the difference between a scripting language and a compiled language? Figure: A compiled program is a process directly controlled by the OS. 8
  • 9. Scripting Languages A scripting language need an interpreter or host. Figure: A interpreted program is a process directly controlled by host which in turn is controlled by the OS. 9
  • 10. Scripting Languages Scripting languages are easier than compiled languages. I A compiled programming language generally has a much larger vocabulary/syntax to learn than a scripted language. There is more to learn. I A compiled programming language is usually conceptually more difficult than a scripted language. Concepts of such as pointers, polymorphism, virtual classes, templating etc. are nontrivial to learn. I There is a bigger burden placed on the programmer using a compiled language. For example, garbage collection or allocating memory when it is needed. I A compiled language is often more “rigid.” This rigidity has its advantages, but also slows coding down.
  • 11. Scripting Languages Scripting languages give “instant gratification.” >> x = 10; >> y = 0; >> x/y; MATLAB will immediately come back with the message “Warning: Divide by zero.” MATLAB is “interpreting” the commands as you type them in. With a compiled language you must compile and link the entire problem and then run it in order to discover the problem. The compilation and linking phase can be very time consuming. You get feedback much faster with the scripting language.
  • 12. Scripting Languages Downside: a scripting application will not run as fast as a compiled application. The scripting language application is running inside the host which is running inside the operating system. When should you use a scripting language? More later! Example scripting languages: 1. Javascript – this scripting language is very popular and is used to add functionality to a browser. Browsers such as Internet Explorer or Firefox serve as the interpreter/host for for Javascript. 2. Visual Basic for Applications (VBA) – this scripting language is immensely popular in the Microsoft world. It is used to add functionality to the suite of Office products. Each Office product such as Excel or Word serves as the host. 3. The MATLAB scripting language and the MATLAB program is the host. 4. Python and an interpreter
  • 13. Scripting Languages Scripting languages make for easy programming. However, there are tradeoffs! A program written in Excel VBA or MATLAB script will not execute as fast as code written in C. There is a performance hit for VBA and MATLAB. Key Idea: YOU must make a decision regarding the tradeoff between execution time and development time. Computers have become so fast in recent years that execution time is becoming less relevant. Hence, software such as MATLAB and Excel/VBA that can shorten the development cycle have become more important.
  • 14. Scripting Languages Development versus execution time. Development Time Execution Time Slow machine Fast machine Figure: Development versus execution time. 14
  • 15. Scripting Languages Other things that are desirable but may slow down either execution or development time include the following. 1. extensive error checking (will slow both development and execution time) 2. putting in extensive documentation (will slow development time, but have no effect on execution time) 3. Using object oriented programming, making extensive uses of classes and polymorphism (will speed development time but slow execution time). 15
  • 16. Scripting Languages On another note: A person in the software industry recently remarked to me that she thought that not all of the decline in jobs for “real programmers” was due to overseas outsourcing. Rather, she felt that because of the proliferation of easy to scripting languages many managers were actually doing programming and they didn’t need real programmers to deal with third generation languages.
  • 17. Tradeoffs – Why VBA? Excel competitors: I MATLAB, Mathematica I SAS, R I Python, Perl Among the scripting languages, why use VBA? Think about Willie Sutton for an analogy?
  • 18. Tradeoffs – Why VBA? VBA is both powerful and flexible. I Build models easily – take input parameters and generate a model instance. I Provide a user interface/GUI so the user doesn’t have to do a lot of work. I Automate tasks through Macros. I Connect to other programs/applications, e.g. a SQL Server or Access database. I Excel with VBA is an IDE – Integrated Development Environment 18
  • 19. Tradeoffs – Why VBA? Excel with VBA is an IDE. Key features include: I There is a VBA editor. This is used for entering VB code. I There is a generic “UserForm” for creating user interfaces. I There a huge function library to select from. You can also write your own functions using VBA. I Excel can be used for statistical analysis. There are routines for calculating means, variances, correlations, running regressions, forecasting models, etc.
  • 20. Tradeoffs – Why VBA? Key features (continued): I You can use Excel for mathematical optimization. We will discuss the GAMS package later in the quarter. I You can use Excel for simulation. I Excel is excellent for creating graphs and histograms. I Excel can import and export data in various formats. It can even read and write XML. I Excel can serve as a database. You can filter and query the data. I You can interface with other programs using Web services.
  • 21. Tradeoffs – Why VBA? VBA, MATLAB, Python – does it really matter which one you learn? No!!! You will learn concepts. I am a former Booth student, and took your VBA/MAtlab class last winter. I just had a job interview that requires the use of Python ... it didnt sound like the tasks they required were that extensive.... Is Python that different from anything we used in class? Thanks in advance for any help you can give.... And if I hadn’t taken your class I wouldn’t even be in the running so thanks for offering it!
  • 22. Brief History The first spreadsheet program for the PC was VisiCal. Created by Dan Bricklin (Harvard MBA student) and his buddy Bob Frankston in 1978. Product was sold and marketed by Dan Fylstra’s (another Harvard MBA) company VisiCorp. It was developed for the Apple II. First “killer app” for the PC. Lotus 1-2-3 was the first big commercial success. I a spreadsheet I a graphics package I a database Microsoft Excel is now the major player in this market.
  • 23. Brief History Microsoft’s first product was a very elementary Basic compiler. Then Microsoft created a widely successful product called Visual Basic. Then Microsoft, in an extremely rare and unusual moment of innovative clarity, combined Visual Basic with Microsoft Office resulting in VBA (Visual Basic for Applications). 23
  • 24. VB Flavors I VB now VB .NET – a programming language that can be compiled into an application. Part of the Microsoft Visual Studio IDE I VBA – a scripting language that uses one of the Office products, e.g. Excel, Word, Power Point, Access as the host. We will use VBA for Excel. I VBScript – the browser, IE Explorer, is the host. Designed to compete with the Netscape Java Script.
  • 26. The VB Editor In order to access the VB editor (Excel 2007) I Click on the Developer Tab in Excel ribbon I Click on Visual Basic to bring up the Editor. If you do not see the Developer Tap click on the Office Button in the upper left-hand corner. Then select Excel Options at the bottom of the window. Make sure ”Show Developer tab in the Ribbon” is selected.
  • 27. The VB Editor Bringing up the Developer Tab 27
  • 28. The VB Editor Code Window Properties Window Project Explorer 28
  • 29. The VB Editor The VB Editor is a set of Windows. You can get a list of available Windows by selecting the View menu item in the VB editor. I The Project Explorer: sort of like the Windows Explorer and allows to explore the files structure of the files in your project. I Projects I Objects – the top level objects such as the Workbook and Worksheets I User Forms – GUIs I Modules – chunks of code that can be executed across worksheets, not necessarily specific to a worksheet.
  • 30. The VB Editor I The Code Window: this is a text editor. You type VBA code in the Code Window. You will spend a lot of time in this Window. I The Properties Window: This will be used later, when we build GUIs. Ignore it for now (although nice if you want to change a module name)
  • 31. The VB Editor Components of the VB Editor (continued) I The Immediate Window Where you go for instant gratification. Y = 4/5 ?Y 0.8 ?Worksheets("Sheet1").Range("amatrix").address $C$5:$D$8 Y=2/3 ?Y 0.66666666666666 Also used for debugging as we see later. I The Watch Window Not now – later, this is good for debugging
  • 32. The VB Editor The VBA editor also contains a set of Toolbars. Again, go to the menu item View and select Toolbars. I Standard Toolbar (play around with the various options) I Edit Toolbar (play around with the various options) I Debug Toolbar (later) I UserForm (later) Go over Chapter 3 in the text several times.
  • 33. Object Oriented Programming Modern programming languages such as C++ and Java are object oriented. Even scripting languages such as VBA have object oriented features. KEY IDEA: develop reusable software modules called objects and make it easy to modify or extend the objects for use in different applications. Object-oriented programming is built around the concepts of a class and an object. A class is an abstraction of a real-world object and describes the essence of the object. For example the concept of a worksheet is a class. A specific worksheet with data is an object in the class. A class is usually composed of 1) properties (often called primitives or data members) and 2) methods (often called functions) that operate on the data. In object speak we say the properties and methods are encapsulated into objects. 33
  • 34. Object Oriented Programming Each of the Microsoft Office family members (Excel, Access, etc.) support VBA. The key difference between the various flavors of VBA is the object model. The Excel VBA object model naturally focuses on the concepts of a Workbook, Worksheet, and Range. What might be some reasonable key objects in Word VBA? For example, kind of object might correspond to a Workbook? 34
  • 35. Object Oriented Programming The two KEY IDEAS for the first part of this course: I The concept of an object I How to work with the range object (next week) 35
  • 36. Object Oriented Programming A fantastic learning aid is the object browser. Spend time with this! The object browser is useful for rookies and experienced veterans alike. 36
  • 37. Object Oriented Programming In the left-most Classes window scroll down and observe the various classes. Select the Worksheet class. In the right window you will see Members of Worksheet. Notice the three different icon types each denoting a different type of member I Properties Member – icons with a hand I Sub Member – green icon I Event Member – lighting bolt icon 37
  • 38. Object Oriented Programming Select the Worksheet class. The Range member is a property of the Worksheet class. The Range is also a class. A class can have a member property that is also a class. Neat! 38
  • 39. Object Oriented Programming Key Idea: Class hierarchy The Workbook class has Worksheet class members. The Worksheet class has Range class members. The Range class has Font class members. The Font class has Size data member (an Variant).
  • 40. Object Oriented Programming The SaveAs member is a sub (I like to call these methods) of the Worksheet class. 40
  • 41. Object Oriented Programming The SaveAs method has arguments. The arguments tell the method how to act. Some arguments are required some are optional []. Sub SaveAs(Filename As String, [FileFormat], [Password], [WriteResPassword], [ReadOnlyRecommended], [CreateBackup], [AddToMru], [TextCodepage], [TextVisualLayout], [Local])
  • 42. Object Oriented Programming The following code illustrates the object oriented nature of VBA. Sub DemoObject() Dim ws As Worksheet Dim rng As Range Set ws = Worksheets("DemoObject") ’A method with no arguments ws.Activate ws.Range("A1") = 99 Set rng = ws.Range("A1") rng.Font.Italic = True ’Set the value of a property ws.Range("A1").Font.Size = 22 ’Methods with arguments rng.Copy Destination:=Range("G1") End Sub
  • 43. Object Oriented Programming: “Dot Notation” Member Specifiction: The notation to specify a member of an object is Object.Member For example, rng.Font or, rng.Calcuate A class member can be a class that has other members. For example: rng.Font.Italic To set the value of a class member that is a property do the following rng.Font.Italic = True 43
  • 44. Object Oriented Programming: Method Specification Method Specifiction: The notation to specify a method of an object for methods with no arguments is Object.Method For example, ws.Activate If the method has arguments the notation is Object.Method Arg1:=Arg1Value, Arg2:=Arg2Value, .. For example: rng.Copy Destination:=Range(”G1”) 44
  • 45. Object Oriented Programming: Method Specification Another way to specify is to drop the argument name, i.e. Object.Method Arg1Value, Arg2Value, .. rng.Copy Range(”G1”) or, when used in an assignment parenthesis Dim money as Currency money = VBA.Format(34.124545, "Currency") 45
  • 46. Object Oriented Psrogramming Intellisense: wow is this great, or what! In the code window type in: Class (object) and all of the members associated the class (object) will pop up in alphabetical order If you type in the name of the method, Intellisense will list the arguments needed, e.g. type MsgBox and hit the space, the arguments to MsgBox will pop up. 46
  • 47. Object Oriented Programming KEY CONCEPTS: I Class I Object I Class Members – the members define the class (properties and methods/procedures) I Method ( also called subroutines, procedures, or functions) I Property – data describing the class I Arguments – inputs to a method/function
  • 48. Generating Code There are three basic ways to generate code: I Import code from a file I Enter code by hand into the code window I Create a macro 48
  • 49. Import Code Open an Excel file that has VBA code and select the Visual Basic Icon in the Developer tab. You will see the code in in the VB editor. Important – Under Macro Security you will need to check the box for Trust Access to the VBA project model. 49
  • 50. Generating Code There are two ways to generate new code. Either type the code into the Code Window by hand or record a Macro. For now we focus on recording macros. Macro – a recording of key strokes and mouse clicks 50
  • 51. Macros After clicking on the record button, the figure below appears. Name the macro and click OK to start recording. When you are done recording your mouse clicks, click Stop Recording icon. 51
  • 52. Macros We can also make a macro available to all workbooks. 52
  • 53. Macros I Download the file vbIntro.xls and select the copyMacro worksheet. I Turn on Macro Recording I Name the macro copyMacro I Highlight the data for ages 30 through 40 I Take the “cross” in the lower left hand side and copy through the age of 60. I Copy cntrl-C I Select Cell D2 I Paste cntrl-V I Select cell A1 I Stop Recording
  • 54. Macros Now go into the VB editor and examine the code. You should have: Sub copyMacro() ’ ’ copyMacro Macro ’ ’ Range("A2:A12").Select Selection.AutoFill Destination:=Range("A2:A32"), _ Type:=xlFillDefault Range("A2:A32").Select Selection.Copy Range("D2").Select ActiveSheet.Paste Range("A1").Select End Sub
  • 55. Macros 1. What is Range? (Object, method, property) 2. What is Select? (Object, method, property) 3. What is Selection? (Object, method, property) 4. What is AutoFill? (Object, method, property) 5. What are the arguments for AutoFill? 6. What are the arguments for Paste
  • 56. Macros I A macro corresponds to code in a module. In particular the macro is a procedure. I The default Module is Module1 – you can change this name in the Properties Window. I A module is code “seen” by all of the spreadsheets. I The name of the procedure corresponds to the name of the macro. I Comments are preceded in VB by a single quote. I We can continue code from one line to the next using an (underscore) 56
  • 57. Macros SUMMARY A sub procedure has the format: Sub SubName() ... VBA Code ... End Sub 57
  • 58. Macros Download the file vbIntro.xls and select the flightMacro worksheet. First understand filtering and sorting. Highlight the entire flight data table. Make sure the Home tab is selected. Then in the ribbon Select Data>Filter Play around and do some sorting and filtering Now deselect Filter so we are back to the original worksheet. 58
  • 60. Macros GENERATING FILTERING MACROS I Step 1: Deselect Filter so we are back to the original worksheet. I Step 2: Start recording a macro named ViewHongKongFlights I Step 3: Highlight the range A3:D15. I Step 4: Select Data>Filter I Step 5: In the Destination column select Hong Kong I Step 6: Select cell A1 I Step 7: Stop Recording
  • 61. Macros GENERATING FILTERING MACROS Your code should look like: Sub ViewHongKongFlights() Range("A3:D15").Select Selection.AutoFilter Selection.AutoFilter Field:=1, Criteria1:="Hong Kong" Range("A1").Select End Sub Edit the ViewHongKongFlights() Sub Procedure so that Beijing flights are viewed instead of Hong Kong flights.
  • 62. Macros CODE GENERATION Do the following: I Based on your understanding of VB create a procedure (without recording a macro) called ViewEconomy that will show all of the available Economy flights. I Test and run these macros
  • 63. Events Events: actions that take place in the Excel window that are linked to code (often called handlers). I Open a workbook I Click on a command button I Activate a worksheet An event procedure is a procedure except that it is associated with an excel event.
  • 65. Events Event Example: the Command Button object. See Developer and Insert Click on the Command Button object and then click somewhere on the spreadsheet. Click on New Create the following code: Sub Button1_Click() MsgBox "Hello World" End Sub 65
  • 66. Events Review: An object is made up of? 66