vba1
vba1
B.A.S.I.C.
Microsoft
origins: if there
is time
B.G .
www.colourbox.com
Visual Basic
Macros
Writing Macros
• You may or may not be able to edit the MS-Word ribbon with
some computer labs.
• You can see view macros via the ‘view’ tab on the ribbon
(albeit with fewer options)
More
secure
Less
secure
JT’s caution
• You should not casually
select this option for all MS-
Word documents
• It’s recommended that you
ONLY enable macros you
have created (or the lecture
examples)
Macro Security
NO!
Less
secure
Creating Macros
Recording Macros
• Developer ribbon
– “Record Macro”
• Give the macro a self explanatory name and press ‘OK’ (recording
begins).
• Note: record the macro in the current document and not “All
documents” (Important!)
– All commands have been entered so you can stop the recording
• After selecting the text and running the macro again, whatever
text was highlighted now becomes bold.
• Drawbacks:
– (Problem in terms of this class) to demonstrate your understanding of
concepts you will be asked to manually write VBA code
• You won’t be adequately prepared if you rely on automatically recording
your programs
– (Problem with doing this in real work) The automatically generated
program code automatically is larger and more complicated than is
necessary
• “Bloated” code
• Look under search terms such as +bloated "vba code" +recorded for
examples of why automating recording VBA programs can be problematic.
Sub headingManual()
Selection.ParagraphFormat.SpaceAfter = 6
End Sub
• Benefits:
– You can use the macro code that is automatically generated in order to
learn how to do manually.
– Sometimes this is very useful if you don’t know the wording of a
command or how to access a property.
– Example (VBA program code for the previous example)
• Record the commands for the macro
• Then view the commands so you can learn how to do it manually
Sub AutoGeneratedFontChange()
Selection.Font.Bold = wdToggle
End Sub
Recording Macros
Program
editor
Undo,
redo
Export:
Run, pause, Current
Useful for stop (VBA location
transferring or subroutine
backing up program)
your work
• Format:
' Program documentation goes here (more on this later)
sub <sub-program name>()
Instructions in the body of program (indent 4 spaces)
End Sub
• Example:
' Author, version, features etc.
Sub first_example_macro_info()
MsgBox ("Congratulations! This your first computer
program")
End Sub
• Note: large VBA programs have multiple (sub) parts but for this
class you only need to define a single ‘sub’.
End Sub
• All executable VBA program statements must be inside the
subroutine
• Learning Objectives:
– Creating/running a VBA program
– Creating a Message Box “MsgBox”
• Reminder steps (since this is your first example)
– Start up the application (MS-Word)
– Invoke the VBA editor: Developer->Visual Basic
• Or you can run the program right after you have entered it (in
the editor).
3. Next you have tell Word that you want to save your macro
program inside this macro-enabled document.
– By default when you save your macros Word will select “Normal.dotm”
as the location.
• DO NOT save your macro in this document:
–You will have trouble transferring your macro to other computers
–Because “Normal.dotm” is the default template used to create some Word documents
it may result in security warnings.
– Instead: Save your macro in your current document (in the example
below it’s “Assignment4.docm”.
• Transferring this document will allow the macros to be transferred as well.
Viewing Macros
• All macros that you have created can be viewed in the VBA
macro editor:
– Macros manually entered in the editor (Message Box example)
– Macros automatically recorded (previous example: changing font to bold)
Previous
macro auto
recorded
• Under the ‘view’ tab uncheck ‘Hide extensions for known file
types’
• You store the macros that you write for this class this way
– In a single document ‘doc-m’ document
• You can also store macros in these documents (not for this
class but important to be aware in terms of computer
security).
– Normal ‘dot-m’ template
– Custom ‘dot-m’ template
Message Box
• Example:
MsgBox ("Congratulations! This your first computer
program")
Notes on ‘Format’:
•Italicized: you have a choice for this part
•Non-italicized: mandatory (enter it as-is)
•Don’t type in the angled brackets (used to help you visually group)
Function arguments
(Bold): mandatory
arguments
Specific
statement/instruction
causing the error (red font)
Real-World Objects
VBA OBject
• Application:
•MS-Word
• Current Document:
•“tamj template”
• Selection
•“Foo!”
• Format:
<Object name>.<method or attribute name>
• Example:
Sub ApplicationTest()
MsgBox (Application.Windows.Count)
End Sub
Property of Window:
Application.Windows.Count • Number
• Recall
– Property: information about an object
– Method: capabilities of an object (possible actions)
Property:
current cell
Using the
‘average()’
function
Methods
Property
• ActiveDocument.SaveAs2("<name>")
Argument: New name of
document needed
More On Objects
Variables
• Used to temporarily store information at
location in memory
• Variables must be declared (created) before
they can be used.
• Format for declaration:
Dim <Variable name> as <Type of variable>
• Example declaration:
Dim BirthYear as Long
1) Any visible character you can type and more e.g., ‘Enter’ key
2) Each string can contain up to a maximum of 2 billion characters
3) Format: Day/month/year
num
num = 1
1
17
num = 17
• Format:
MsgBox ("<Message1>" & <variable name>)
• Example:
Dim num as Long
num = 7
MsgBox ("num=" & num)
Option Explicit
• Learning Objectives:
– Using variables
– Using mathematical operators
Sub thirdExample()
Dim RealNumber As Double
Dim WholeNumber As Integer
RealNumber = 1 / 3
MsgBox (RealNumber)
WholeNumber = 5 / 10
MsgBox (WholeNumber)
WholeNumber = 6 / 10
MsgBox (WholeNumber)
End Sub
Student Exercise #1
Student Exercise #2
num1 = 10
num2 = 10.5
num1 = num2 + 10
num2 = num1 * 2 / 3
MsgBox (num1 & "---" & num2)
End Sub
• Language requirements:
– Rules built into the Visual Basic (recall VBA is essentially Visual Basic
tied to an MS-Office Application) language.
– Somewhat analogous to the grammar of a ‘human’ language.
– If the rules are violated then the typical outcome is the program
cannot execute.
• Style requirements:
– Approaches for producing a well written program.
– (The real life analogy is that something written in a human language
may follow the grammar but still be poorly written).
– If style requirements are not followed then the program can execute
but there may be other problems (e.g., it is difficult to understand
because it’s overly long and complex - more on this during the term).
1 http://msdn.microsoft.com/en-us/library/ms229045.aspx
#4
4. Style requirement: For names firstName, last_name
composed of multiple words (yes to either approach)
separate each word by
capitalizing the first letter of
each word (save for the first
word) or by using an underscore.
(Either approach is acceptable
but don’t mix and match.)
After
• Format:
ActiveDocument.ActiveWindow.Caption =
"<New text for the title bar>"
– Overuse can simply result in the user “clicking past” the dialog without
reading them
• Status messages:
– More subtle presentation of information.
– Easy to miss.
– Multiple updates result in only the last change appearing to the user
num1 = 666
num2 = 888
ActiveDocument.ActiveWindow.Caption = num1
ActiveDocument.ActiveWindow.Caption = num2
End Sub
• Example:
Name = InputBox("What is your name"), "Getting Personal")
Example: InputBox
• Learning: getting user input with an InputBox
• Word document containing the macro:
6inputBox.docm
Sub InputExample()
Dim Age As Integer
Dim Name As String
Dim DogAge As Integer
Name = InputBox("What is your name", "Getting personal: name")
Age = InputBox("What is your age", "Getting even more personal: age")
DogAge = Age * 7
MsgBox (Name & " your age in dog years is " & DogAge)
End Sub
Note: there are two input boxes, one that prompts for the name and the other
for the age. Each is given a self-descriptive name to distinguish them (an
example of good programming style – more on this shortly)
• Multiple breakpoints
Named Constants
• Format:
Const <Name of constant> = <Expression>1
• Example:
Sub ConstantExample()
Const PI = 3.14
End Sub
1 The expression can be any mathematical operation but can’t be the result of a function call
Closing Documents
Pre-defined constant
Sub ClosingActions()
ActiveDocument.Close (<Constant for closing action>)
End Sub
Formatting Text
• Now for the ‘selected text’ (in this case it’s the whole
document) access the ‘Font’ property and the ‘Name’
property of that font and give it the desired name.
Selection.Font.Name = "Calibri"
Sub cutAndPaste()
Selection.Expand
Selection.Copy
Selection.MoveRight
Selection.PasteAndFormat
(wdFormatOriginalFormatting)
End Sub
• A predefined constant
• Another is
“wdFormatPlainText”
Student Exercise #3
• Desired formatting:
– Font size = 14 point
– Bold
– Underline
– Center the heading
– 6 point spacing after the heading
• Word document name:
10formattingSelectedTextMultiple.docm
Sub formattingHeadings()
Selection.Font.Size = 14
Selection.Font.Bold = True
Selection.Font.Underline = True
Selection.ParagraphFormat.Alignment =
wdAlignParagraphCenter
Selection.ParagraphFormat.SpaceAfter = 6
End Sub
Effect
• Before:
• After
• Desired formatting:
– Font size = 10 point
– Left and right margins indented by 0.2 inches
• Word document: 11formattingSelectedParagraphs.docm
Sub formattingParagraphs()
Selection.Font.Size = 10
Selection.Font.Bold = True
Selection.ParagraphFormat.LeftIndent = InchesToPoints(0.2)
Selection.ParagraphFormat.RightIndent = InchesToPoints(0.2)
End Sub
Formatting: Recap
Program Documentation
• Program documentation
– ' Author: James Tam ID: 123456
– ' Version: Nov 2, 2015
– ' Tutorial: 99
– ' PROGRAM FEATURES
– ' Word search and replace: completed
– ' Style search and replace: not completed
– etc
• Where?
• Right with your program before the ‘option explicit’
A Source Of Help
Recorded Macros
Copyright Notice