Excel VBA Course Exercises 14-3-13
Excel VBA Course Exercises 14-3-13
On the developers tab make sure that use relative cell references
is highlighted, on the developer tab click on the macro security
button. For the purpose of the course we shall take security off.
Note:
1
Excel VBA Introduction – Course Exercise
The recorded name for the macro, cannot start with numbers
and have no spaces.
2
Excel VBA Introduction – Course Exercise
3
Excel VBA Introduction – Course Exercise
Select Cell D1
From the status bar select record macro
Define the name as Bestfit (no space)
Create keyboard shortcut CTRL+B
Save in this workbook
Click Ok to continue
From the home tab on the ribbon on the right side select
format, AutoFit column width
Click Stop recording on the status bar.
Select cell F3 press CTRL+B to run the best fit macro, try on
two other cells only (do not format the entire workbook at this
point.)
4
Excel VBA Introduction – Course Exercise
Select Cell B1
From the status bar select record macro
Define the name as Patterns
Create keyboard shortcut CTRL+P
Save in this workbook
Click Ok to continue
Change the cell colour to Yellow
Click Stop recording on the status bar.
Select cell C1 press CTRL+P to run the Patterns macro, try on
two other cells only (do not format the entire workbook at this
point.)
5
Excel VBA Introduction – Course Exercise
Select Cell E10 use the shortcut keys to format the cell
Please note the recordings that you have made so far have been
relative recordings, macros that apply the recorded formats to
cells that you select relative to the cursor position. Care has to be
taken when recording relative macros because you can cause an
error by trying to access areas outside the work sheet, the next
example is set up to do that deliberately.
Select Cell H1
Switch to the developer tab make sure relative cells is
highlighted before we proceed.
Click record macro
Define the name as Error
Create keyboard shortcut CTRL+E
Save in this workbook
Click Ok to continue
Change the cell colour to green
Select Cell E1
Change the cell colour to Red
Click Stop recording on the status bar.
6
Excel VBA Introduction – Course Exercise
Note run time errors are not that informative searching the web
for error 1004 will bring back many answers if you are lucky you
may find an answer for this example we shall click on debug.
7
Excel VBA Introduction – Course Exercise
Exercise 6 10 mins
Select Sheet 2
Type your name into cell A1drag down to A10 then across to
column H10
Select Cell E5
From the status bar select record macro
Define the name as shadings
Create a shortcut Ctrl + S save into personal workbook
Click ok to continue
Change the cell colour to Blue
Click Stop recording on the status bar.
Note you will have to display hidden folders to locate the folder
through windows explorer this is for win 7 office 2010.
C:\Users\mouse\AppData\Roaming\Microsoft\Excel\XLSTART
8
Excel VBA Introduction – Course Exercise
Delete module 1
Try The macro Again it should have disappeared
So far you have run macros from shortcuts and the macro dialog
box, next we shall set up an icon in the Ribbon, UAT and add a
button to the excel Worksheet
9
Excel VBA Introduction – Course Exercise
Exercise 7 5 mins
10
Excel VBA Introduction – Course Exercise
Exercise 8 5 mins
11
Excel VBA Introduction – Course Exercise
Exercise 9A
Add a button to the spread sheet Form Controls
Form Controls
12
Excel VBA Introduction – Course Exercise
Exercise 9B
Add a button to the spread sheet Active X Controls
Active X Controls
End Sub
Modify the code adding the Call Function as shown below whee
as macroxyz represents the name of the macro you want to
run.
Call macroxyz
End Sub
13
Excel VBA Introduction – Course Exercise
Open the properties window for the button from either the
ribbon bar on from right clicking on the mouse.
In the properties dialog box navigate to caption, type in My
first X Control.
Close the properties box
Click the design view button to enter real time you can now
click on your button to run the macro.
14
Excel VBA Introduction – Course Exercise
Exercise 10
Delegate exercise
Close and open Excel
Enter random numbers from A1 to H9
Record a macro to format numbers as currency
Record a macro to change cell colour to blue
Record a macro to change Text colour to white
Assign the three macros to the toolbars UAT and Ribbon
Create a new macro using a command button Use the call
button to run the macros
Create a new form button and assign macros
Create a macro in your personal work book to format dates in
the dddd dd mmmm yyyy format. Assign to your toolbar
Use logic to see if you can assign all three macros to the
command button.
At the end of this section you can now record a macro in both
absolute and relative Mode, Know the difference between
personal workbooks and macros stored in work Books. launch
macros from either the dialog box, short cut key, toolbar, Form
button or active X button and have had exposure to the VBA
window we can see that recorded macros are powerful but are
limited in their use relying on user activation. Using VBA we can
introduce data validation, actions on events and automaton.
15
Excel VBA Introduction – Course Exercise
What is VBA?
In short Microsoft Programming language to control actions of a Microsoft
product, whilst All VBA has some basic fundamentals it differs for each
Product . VBA is a subset of VB, IN VBA all the hard work is done we
manipulate what is available to us in VB you start from scratch.
VBA Terminology
Procedures
Object
Property
Each object in VBA has its own properties that control its
appearance typical properties – column width, row height, font,
text, value, formula, borders
Method
Comment
16
Excel VBA Introduction – Course Exercise
Module
Execute
Collections
Containers
17
Excel VBA Introduction – Course Exercise
18
Excel VBA Introduction – Course Exercise
Range("A1") Cell A1
[A1] Cell A1
19
Excel VBA Introduction – Course Exercise
Square brackets
The full object reference to the worksheet cell A1 is Range("A1"). If you are
typing-in cell
references rather than recording, it is easier to use the shortcut notation
using square
brackets, [A1]. You can use the same style of referencing on other objects as
well, such
as worksheets but there are a number of rules and restrictions.
It is usually best to restrict the square bracket notation to cell references
only, where it is entirely definitive and reliable.
With…End With
The With statement is used so the object reference can be made and then
retained so that multiple actions may be carried out without having to
repeat the same object reference in each statement.
You can keep the With reference open for as long as you like in the same
procedure, just pointing to it using the dot operator. Every With requires
an End With. You can have
multiple With pointers. When you are reading code that uses multiple With
pointers, the rule is simple; the dot points to the nearest With.
With Object
.Property
With .Child Object
.Method
.Method
End With
End With
20
Excel VBA Introduction – Course Exercise
Exercise 11
Explore The VBA Editor
Open the file Budget Report Access the Excel VBA window by
clicking ALT + F11
Project Explorer
21
Excel VBA Introduction – Course Exercise
Properties window
Lists all the properties of the selected object
Immediate Window
Watch Window
22
Excel VBA Introduction – Course Exercise
Exercise 12
properties window
In the scroll area type the following values and then switch
windows to see the effect
$A$1
$E$16
$A$1:$E$16
23
Excel VBA Introduction – Course Exercise
Exercise 13
Code window, object list and procedure list
General
WorkSheet
End Sub
24
Excel VBA Introduction – Course Exercise
Exercise 14
Identify the colours in the code Window
Sub showingcolours()
MsgBox "rot"
Call macro3
End Sub
25
Excel VBA Introduction – Course Exercise
Exercise 15
Using Methods
Every object can perform certain actions are defined by methods. Some
methods need a value as input to complete their actions. For example, the
open method of the workbook object takes a file name as input so it knows
specifically what workbook to open. The input value is called an argument.
An argument is a variable, constant or expression that provides additional
information to a method, so that it can execute properly. To use a method
in VBA code, you would use the following syntax.
Sub password_on( )
Sheet2.protect “password”
End Sub
Sub password_off( )
Sheet2.unprotect “password”
End sub
Sub password_off( )
Sheet2.unprotect
End sub
Note if you use option B you are prompted for your password in
the form of a dialogue box
26
Excel VBA Introduction – Course Exercise
Exercise 16
Responding to an Event
Each time you select sheet 2 the worksheet is locked click the
button unprotect and enter the password “password” to unlock.
27
Excel VBA Introduction – Course Exercise
Exercise 17
Add a message box to the code
Sub password_on( )
Sheet3.protect “password”
Msgbox “Protected worksheet. You cannot edit data in this list
End Sub
Exercise 18
Delegate Exercise
Exercise 19
Use row and column references
Sub Calculate()
ActiveCell.FormulaR1C1 = "=Product(rc[-2]:rc[-1])"
End Sub
With
ActiveCell.FormulaR1C1 = "=sum(rc[-2]:rc[-1])"
Try
ActiveCell = "=sum(a1:a5)"
28
Excel VBA Introduction – Course Exercise
End Sub
Sub F123()
Dim x as Integer
Dim y as Integer
x = [A1]
y = [B1]
MsgBox "Add a1" & vbNewLine & "and B2 together" & vbNewLine & "The
value is " & x + y
End Sub
Sub fig1()
text1 = "Hello"
End Sub
29
Excel VBA Introduction – Course Exercise
Sub fig2()
MsgBox Left(text, 4)
End Sub
Sub fig3()
MsgBox Right(text, 4)
End Sub
Sub fig4()
MsgBox Mid(text, 3, 2)
End Sub
Sub fig5()
MsgBox "using the mid function the text mpl is at position " & InStr(text,
"mpl") _
End Sub
30
Excel VBA Introduction – Course Exercise
Exercise 20
Explore the object browser
The Object Browser enables you to see a list of all the different objects with
their methods, properties, events and constants.
The default libraries available:
Excel – A collection of classes available in Excel i.e. workbook, worksheet,
range, chart, etc…
Office – A collection of classes generic to all office applications i.e. command
bar, command icon, help assistance, etc…
stdole – A collection of standard OLE classes which allow other OLE
applications to share information (Not covered in this manual).
VBA – A collection of classes which allow generic functions to be used i.e.
MsgBox, InputBox, conversion functions, string functions, etc…
VBAProject – A collection of classes local to the active workbook project,
which includes sheets, workbook and any user, defined classes
31
Excel VBA Introduction – Course Exercise
32
Excel VBA Introduction – Course Exercise
Programming Basics
Data
Programs receive data as input then process the data as output, a good
example is a calculator where you input numbers and instruct it which
operator to use, when inputting data the program uses a temporary storage
area called a variable, variables can be defined as different types a full
listing on page 14 of the user manual.
Exercise 21
Implicit Variables (not declared prone to errors)
Sub calc ( )
Msgbox(anser)
End Sub
33
Excel VBA Introduction – Course Exercise
Let’s try that again making sure that the variable is the same in
both places.
Sub calc ( )
Msgbox(Answer)
End Sub
As you can see this time we come back with the correct result
but as we have discovered it is prone to mistakes let’s try
something different type in the following code
Variable option explicit (the name for the variable has to be declared)
Option Explicit
Sub calc()
MsgBox (Anser)
End Sub
Run the code press the play button or press F5 this time the
message box below displays showing the variable name has
not been declared we need to
add the following line of code.
“Dim answer As Byte”
Sub calc()
Dim answer As Byte
answer = 100 + 100
MsgBox (answer)
End Sub
34
Excel VBA Introduction – Course Exercise
Option Explicit
Sub calc()
Dim answer As Byte
answer = 100 + 200
MsgBox (answer)
End Sub
Run the code again, this time you will get an overflow error
Change the data type to remedy this problem, try integer -32,768 to
Option Explicit
Sub calc()
End Sub
35
Excel VBA Introduction – Course Exercise
You may wish to change the font size in the VBA editor, select
Editor Format Tab to change font attributes.
Exercise 22
Variable Constant (a variable that doesn’t change)
Option Explicit
Const vat = 0.20
Sub calc()
Dim answer As Integer
answer = (100 + 100) * vat
MsgBox (answer)
End Sub
Option Explicit
Const vat = 0.21
Sub calc()
End Sub
36
Excel VBA Introduction – Course Exercise
Option Explicit
Const vat = 0.21
Sub calc()
Dim answer As Currency
answer = (100 + 120) * vat
MsgBox "£ " & (answer)
End Sub
Exercise 23
understanding Expressions and operators
Expressions
An expression is a combination of operators, constants, procedures and names
of controls and properties that is evaluated to obtain a result. When you use
an expression in code it returns a value in one of the data types provided by
VBA.
Operators
Operators are arithmetic symbols
Arithmetic Operators Comparison Operators
+ Addition < Less than
- Subtraction > Great than
/ Division = Equal to
* Multiplication <> Not equal to
A comparison operator returns a Boolean value because the result of any
comparison is always true or false
37
Excel VBA Introduction – Course Exercise
Visual Basic
Nominal storage allocation Value range
type
0 through +/-
Decimal 16 bytes 79,228,162,514,264,337,593,543,9
50,335 (+/-7.9...E+28) †
-1.79769313486231570E+308
Double 8 bytes through -4.94065645841246544E-
324 †
-2,147,483,648 through
Integer 4 bytes
2,147,483,647 (signed)
-9,223,372,036,854,775,808
Long (long through
8 bytes
integer) 9,223,372,036,854,775,807
(9.2...E+18 †) (signed)
Short (short
2 bytes -32,768 through 32,767 (signed)
integer)
String
0 to approximately 2 billion
(variable- Depends on implementing platform
Unicode characters
length)
38
Excel VBA Introduction – Course Exercise
Exercise 24
The cells object
The cell object syntax cells (row, column) operates similar to the index
function the main difference between the cell object function is unlike the
excel functions that call column first then row, the cell object calls the row
first then the column.
Push or Pull
In the code window type the following code this will populate
the cell D2 with 2012
Sub push()
Cells(2, 4).Value = 2012
End Sub
In the code window type the following code this will retrieve
information from cell D2
Sub pull()
Dim myvar As Integer
myvar = Cells(2, 4).Value
End Sub
Now we have run the code we can’t see straight away that the value has
been place we shall use two methods to extract that data one is to use
the locals window and set toggle points on the code and the other is to
modify the code to output the data to a message box.
Modify the code as below to output results to a message box.
Sub pull()
Dim myvar As Integer
myvar = Cells(2, 4).Value
MsgBox (myvar)
End Sub
39
Excel VBA Introduction – Course Exercise
40
Excel VBA Introduction – Course Exercise
Exercise 25
In the code window type the following
Sub inbox()
'opens a message box and joins text to a variable then joins to text and
displays an information button
MsgBox "you have placed the text " & (employee) & " in cell D2",
vbInformation
End Sub
As you can see you are building up your use of knowledge and little by little
building on what you learn at each stage.
41
Excel VBA Introduction – Course Exercise
Exercise 26
Create the following example you are going to collect the following
information
Name
Surname
Job
Salary
Date of birth
Calculate age
"you have applied for job of " XYZ " and require a salary of " £ XYZ
After you complete the information your screen should look like below
By the end of the course you would have learnt how to go to the
next available blank row and use a form rather than input boxes
to enter the data.
42
Excel VBA Introduction – Course Exercise
Exercise 26 Answer
Sub job()
Dim name As String
Dim surname As String
Dim job As String
Dim salary As Currency
Dim birth As Date
Dim age As Double
curdate = Date
name = InputBox("enter your first name")
surname = InputBox("enter your Surname name")
job = InputBox("enter your required Job")
salary = InputBox("enter required salary")
birth = InputBox("enter date of birth dd/mm/yy")
Cells(2, 1).Value = name
Cells(2, 2).Value = surname
Cells(2, 3).Value = job
Cells(2, 4).Value = salary
Cells(2, 5).Value = birth
43
Excel VBA Introduction – Course Exercise
Exercise 27
Concatenating text (joining cells text and variables)
To combine variables with text use the concatenation operator, ampersand (&)
Sub join()
Dim Amount As Integer
Amount = InputBox("enter a value")
MsgBox "The Amount is:" & "£" & amount
End Sub
The code above takes the value you enter in an input box, then
displays that as The amount is £90 that is on the assumption
you have typed 90 into the input box.
Sub usingfunctions()
Dim saleseast As Integer, saleswest As Integer, sum As
Integer
MsgBox "please enter whole numbers only"
saleseast = InputBox("enter the total sales for the east")
saleswest = InputBox("enter the total sales for the west")
sum = saleseast + saleswest
Cells(2, 4).Value = sum
MsgBox "total sales for east and West: £" & sum
End Sub
44
Excel VBA Introduction – Course Exercise
Exercise 28
Object variables
Make sure you spell Color, the way it’s shown not the uk version
Sub changewkstabcolour()
Dim wks As Worksheet
Set wks = ThisWorkbook.Worksheets("sales2011")
wks.Tab.Color = vbRed
Set wks = ThisWorkbook.Worksheets("sales2012")
wks.Tab.Color = vbGreen
End Sub
The code above sets variable WKS as a worksheet object, worksheets are a
member of the workbook family, and inside the parentheses we define the
worksheet name. The property of the tab is changed by referencing the
object variable and setting the property to the appropriate colour.
Sub changetabsales ()
ThisWorkbook.Worksheets ("sales").Tab.Color = vbBlue
ThisWorkbook.Worksheets ("sales2011").Tab.Color = vbGreen
ThisWorkbook.Worksheets ("sales2012").Tab.Color = vbRed
End Sub
Sub changecol ()
Sheets (ActiveSheet.Name).Select
ActiveWorkbook.Sheets (ActiveSheet.Name).Tab.ColorIndex = 21
End sub
The code above changes the tab colour of the active sheet
45
Excel VBA Introduction – Course Exercise
Exercise 29 Explanation
Declarations section
The top of the code window includes a declaration section; variables placed here can be
used by all procedures within the module remember option explicit is also set in this area.
Scope of variables
Three types of scope are available in VBA as already stated the scope of a
variable is determined by the way you declare it.
46
Excel VBA Introduction – Course Exercise
Exercise 29
Calling a sub procedure
Option explicit
Public Function CalculateSalesTax() As Currency
'CalculateSalesTax = Cells(5th row, 4th column)=D5.Value * 0.08
CalculateSalesTax = Cells(5, 4).Value * 0.08
End Function
In the code window set up the code below this calls the
function calculatesalestax
End Sub
Exercise 30
Function procedure
47
Excel VBA Introduction – Course Exercise
Syntax Components
Function and End function specify the start and finish of the
function procedure
Function <procedure Name>, this gives the function its name,
the name has to be unique and cannot be a VBA keyword.
As <data type>. Though optional if not declared the variables
are set to variant remember we said earlier code is more
efficient when specified.
<Procedure Body> the lines of code within the function that
make up the function and that are executed in sequential steps.
48
Excel VBA Introduction – Course Exercise
Exercise 31
Calling function procedures
Option Explicit
End Function
PublicSub main ()
Call sales
End Sub
Select Cell
49
Excel VBA Introduction – Course Exercise
Exercise 32
Calling a user defined function
This has now given you an insight to the program basics, we shall
now move on to Control and decision structures
50
Excel VBA Introduction – Course Exercise
Control Structures
Exercise 33
Control Structures
Overview
Exercise 34
If..then…else construction
The control structure that offers all these possibilities is the If...Then...Else
Statement in (VBA). You can use a single-line version if you have just one
test and one statement to run. If you have a more complex set of conditions
and actions, you can use the multiple-line version.
51
Excel VBA Introduction – Course Exercise
Sub test ()
If condition Then
[statements]
ElseIf elseifcondition Then
[ elseifstatements ]
Else
[ else statements ] ]
End If
End sub
Sub test ()
End Sub
Syntax property Terminology
Condition
Required. Expression. Must evaluate to True or False, or to a data type
that is implicitly convertible to Boolean.
Then
Required in the single-line form, optional in the multiple-line form.
Statements
Optional. One or more statements following If...Then that are executed if
condition evaluates to True.
Elseif condition
Required if ElseIf is present. Expression. Must evaluate to True or False,
or to a data type that is implicitly convertible to Boolean.
Elseif statements
Optional. One or more statements following ElseIf...Then that are
executed if elseifcondition evaluates to True.
Else statements
Optional. One or more statements that are executed if no previous
condition or elseifcondition expression evaluates to True.
End If
Terminates the If...Then...Else block.
52
Excel VBA Introduction – Course Exercise
Exercise 35
In this procedure we check cell reference A1 to check to see if the vale is
Less than 100 if the cell evaluates less than 100 the function is deemed as
true and places the message Low otherwise no action taken
If then statement
Alternative Code
Sub testb()
If Cells(1, 1).Value < 100 Then
Cells(1, 2).Value = "poor"
End If
End Sub
Using the cell reference letter ,number
Alternative Code
Sub testc()
If [a1] < 100 Then
MsgBox "low"
End If
End Sub
Alternative Code
Sub testd()
If [a1] < 100 Then
[a2]=”poor”
End If
End Sub
53
Excel VBA Introduction – Course Exercise
Exercise 36
In this procedure we check cell reference E4 to check to see if the vale is
greater than 100 if the cell evaluates greater than 100 the function is
deemed as true and places the message “very high mpg” in cell E4 at the
end if it breaks out and continues to run the remainder of the procedure, in
this case places "Very Low MPG" value in cell f4
If then else statement
Sub teste()
If Cells(4, 5).Value > 100 Then
Cells(4, 6).Value = "Very high MPG"
Else
Cells(4, 6).Value = "Very Low MPG"
End If
End Sub
Alternative Code
Using the cell reference letter ,number
Sub testf()
If [e4] > 100 Then
[f4] = "Very high MPG"
Else
[f4] = "Very Low MPG"
End If
End Sub
54
Excel VBA Introduction – Course Exercise
Exercise 37
If then elseif else statement
With the previous examples this has the same effect as using an if
statement in a formula in the spreadsheet, in the next example we
look at what we consider to be a nested if, using the
Alternative Code A
Using the cell reference letter ,number
Sub testh()
If [E4] <= 10 Then
MsgBox "change car"
ElseIf [E4] <= 40 Then
MsgBox "Expensive to run"
ElseIf [E4] <= 80 Then
MsgBox "average mpg achieved"
ElseIf [E4] <= 90 Then
MsgBox " above average mpg your now saving"
Else
MsgBox "well done you have gone Electric"
End If
End Sub
55
Excel VBA Introduction – Course Exercise
Alternative Code B
Using the cells reference row, column
Sub testi()
If Cells(4, 5).Value <= 10 Then
Cells(4, 6).Value = "change car"
ElseIf Cells(4, 5).Value <= 40 Then
Cells(4, 6).Value = "Expensive to run"
ElseIf Cells(4, 5).Value <= 80 Then
Cells(4, 6).Value = "average mpg achieved"
ElseIf Cells(4, 5).Value <= 90 Then
Cells(4, 6).Value = " above average mpg your now saving"
Else
Cells(4, 6).Value = "well done you have gone Electric"
End If
End Sub
Alternative Code c
Using the cell reference letter ,number
Sub testj()
If [E4] <= 10 Then
[f4]="change car"
ElseIf [E4] <= 40 Then
[f4]= "Expensive to run"
ElseIf [E4] <= 80 Then
[f4]="average mpg achieved"
ElseIf [E4] <= 90 Then
[f4]=" above average mpg your now saving"
Else
[f4]= "well done you have gone Electric"
End If
End Sub
56
Excel VBA Introduction – Course Exercise
Exercise 38 A
Select case statement
Sub case1()
x = [A1]
Select Case x
Case Is <= 100
y = "Small"
Case 101 To 250
y = "medium"
Case Else
y = "large"
End Select
[a2] = y
End Sub
57
Excel VBA Introduction – Course Exercise
Exercise 38 B
Select case statement
Sub Using_Case()
' Test to see if x less than or equal to 40 and greater than 10.
Case 11 To 40
MsgBox "X is <=40 and > 10"
' Test to see if x less than or equal to 70 and greater than 40.
Case 41 To 70
MsgBox "X is <=70 and > 40"
' Test to see if x less than or equal to 100 and greater than 70.
Case 71 To 100
MsgBox "X is <= 100 and > 70"
End Sub
58
Excel VBA Introduction – Course Exercise
Exercise 38 C
Sub Using_Case()
' Test to see if x less than or equal to 40 and greater than 10.
Case Is <= 40
MsgBox "X is between 11 and 40"
' Test to see if x less than or equal to 70 and greater than 40.
Case Is <= 70
MsgBox "X is between 41 and 70"
' Test to see if x less than or equal to 100 and greater than 70.
Case Is <= 100
MsgBox "X is between 71 and 100"
End Sub
59
Excel VBA Introduction – Course Exercise
Exercise 38
Two functions that can be used in VBA, Choose and Switch
Sub main()
x=1
y = Choose(x, "tom", "dick", "harry")
MsgBox y
End Sub
Switch evaluates list of pairs of expressions and values and returns the
value associated with the first expression in the list that is true.
Sub maina()
x = "usa"
y = Switch(x = "uk", "£ Pound", x = "usa", "$ Dollar", x = "esp", "€ Euro")
MsgBox y
End Sub
60
Excel VBA Introduction – Course Exercise
Looping Structures
Exercise 39
Examine Loop structures
You use loop structures such as for… next and for each …next when you
want to run a specific block of text repeatedly. Use one of two loop
structures depending on the number of iterations that are required.
Fixed iteration This runs a set of statements for a predetermined number
of times. Example For… next loop
Indefinite Iteration this runs a set of statement until a defined condition is
met.
in the example below the numbers add up 1 +2+3 to give a result of 6 if you
substitute for count 1 to 3 with for count 1 to 10 the numbers added
1+2+3+4+5+6+7+8+9+10 resulting in the value 55 returned. You could run
for count 6 to 7 this adds 6+7 for count 6 to 9 this adds 6+7+8+9.
Exercise 40
Type in the following code the answer should be 6
61
Excel VBA Introduction – Course Exercise
Exercise 41
Type in the following code the answer should be 60
62
Excel VBA Introduction – Course Exercise
Exercise 42
consider a nested if function and how we can convert it into code.
=IF(A1<500,A1*0,IF(A1<=1000,A1*10%,A1*30%))
Sub count2()
‘set the variable name
Dim count As Integer
‘instruct how many times to loop
For count = 1 To 20
'each time the loop runs it passes the number into count in the cells
range on the next line
'the number increases with each loop through 1 to 20
totalsales = Cells(count, 1).Value
End Sub
63
Excel VBA Introduction – Course Exercise
Exercise 43
The for… each next loop
Sub CommandButton1Click()
‘sets I and j as variables
Dim i, j As Integer
'will run for 20 rows
For i = 1 To 20
'will run for 12 columns
For j = 1 To 12
'accepts number position from cells above and preforms the calculation
Cells(i, j).Value = i + j - 1
'instructs the code to loop until criteria is met
Next j
Next i
End Sub
Sub CommandButton2Click()
‘sets I and j as variables
Dim i, j As Integer
'will run for 20 rows
For i = 1 To 20
'will run for 12 columns
For j = 1 To 12
'accepts number position from cells above and preforms the calculation
Cells(i, j).Value = i * j
'instructs the code to loop until criteria is met
Next j
Next i
End Sub
64
Excel VBA Introduction – Course Exercise
Exercise 44 A
Do while loop
Now we introduce you to Conditional Loops Repetition while a certain
condition is satisfied or until a certain condition is satisfied.
Type the code below into the VBA code window this sets x as a
variable do while x<40 sets the criteria
Take the value of X and add 7 to it
Display message box until criteria is met
Sub doloopwhile()
x = 10
Do While x < 40
x=x+7
MsgBox x
Loop
End Sub
Sub doloopuntil()
x = 10
Do Until x > 40
x=x+7
MsgBox x
Loop
End Sub
65
Excel VBA Introduction – Course Exercise
Exercise 44 B
Do while loop
Use the code below each number in a cell will be doubled text
will be cleared.
Sub ForEachCollectionLoop2()
For Each cell In Range("A1:G50")
If IsNumeric(cell) Then
cell.Value = cell.Value * 2
Else
cell.Clear
End If
Next
End Sub
Exercise 45
The for… each next loop
Sub CommandButton1_Click()
Dim i, j As Integer
For i = 1 To 20
For j = 1 To 12
Cells(i, j).Value = i * j
Next j
Next i
End Sub
66
Excel VBA Introduction – Course Exercise
Exercise 46
Custom Dialog Boxes The Process
User Forms
Display interactive dialogs in the Excel interface by including a User Form
in your project.
The programming of User Forms can be time-consuming as every action
that the User
Form performs has to be coded, the OK button does not do anything until
you write the
code contained in its click event.
You need to be familiar with User Form objects, there is no macro recorder.
Designing the User Form
The general methodology for designing User Forms is as follows:
Insert a User Form into your Project.
Create the visual image by adding Controls to the Form.
Name the Controls and set their static properties.
Write the code in your General Module to show the User Form.
Fill in the event code shells in the User Form’s object module.
67
Excel VBA Introduction – Course Exercise
Exercise 47A
Adding a user form, we are going to take steps to create the form below to accept
new data and paste it to the next available row.
68
Excel VBA Introduction – Course Exercise
Exercise 47B
Laying out user Controls (user controls explained) and change property settings
69
Excel VBA Introduction – Course Exercise
70
Excel VBA Introduction – Course Exercise
71
Excel VBA Introduction – Course Exercise
72
Excel VBA Introduction – Course Exercise
73
Excel VBA Introduction – Course Exercise
The Design of the form is now complete Now let us see what it
looks like in real time mode
74
Excel VBA Introduction – Course Exercise
frmemployeeinfo.Hide
End Sub
You have added some events to your buttons we shall now explore events
even more throughout the following exercises
75
Excel VBA Introduction – Course Exercise
Understanding Events
VBA is based around event – driven programming. In other words the code
doesn’t follow a predetermined path, instead it responds to events that a
user or condition that occurs. For example the click of a button generates
an event, the on_click event. Procedures are executed when an event is
triggered. User forms and their controls respond to the events that are
associated with them. Below is a list of events and their triggers.
76
Excel VBA Introduction – Course Exercise
Exercise 48
Event handling code
Attach an event handler to a control
Double click on the command button Submit Data the code window opens
as below.
Add the following code to read as below this stores the data from the form
Exercise 49
Adding a combo box for department
77
Excel VBA Introduction – Course Exercise
Click on show form in the excel window, enter data and click
submit, the data should be entered onto the spreadsheet.
Use this code on drop button click event to populate combo box list
End Sub
78
Excel VBA Introduction – Course Exercise
Exercise 50a
Use the code below to add data to the next line in a spreadsheet
frmemployeeinfo.Hide
End Sub
Exercise 50b
To elaborate and introduce further data validation maybe add code as
detailed below.
Cancel = True
Cancel = True
Cancel = True
Cancel = True
79
Excel VBA Introduction – Course Exercise
Cancel = True
Else
nextrow = Application.WorksheetFunction.CountA(Range("a:a"))
Unload Me
frmemployeeinfo.Show
End If
End Sub
Exercise 51
Data validation
If a user accidently enters the wrong data or data is missing we want to be
able to set in place some rules of checking that information, this is known
as validation. Navigate to the VBA Editor window we are going to set
up the following validations.
sets 2 values in the drop down list as soon as you start typing in to employee name.
“select from list”
80
Excel VBA Introduction – Course Exercise
Checks to see if there is text in Employee Name if not a message box is displayed ,
when you click ok on the message box, focus is placed back to the cell to re-enter
the data
End Sub
81
Excel VBA Introduction – Course Exercise
Exercise 52
Form check List
Before you unleash your UserForm, give it one final check using the
following checklist.
Are the controls aligned with each other?
Are similar controls the same size?
Are controls evenly spaced?
Is the dialog box too overwhelming? If so, you may want to use a series
of dialogs (like a Wizard), or use a Multipage control.
Can every control be accessed with an accelerator key?
Are any of the accelerator keys duplicated?
Are the controls grouped logically (by function)?
Is the tab order set correctly? The user should be able to tab through
the dialog box and access the controls sequentially.
If the UserForm will be stored in an add-in, did you test it thoroughly
after creating the add-in? It's important to remember that an add-in
will never be the active workbook.
Will your VBA code take appropriate action if the UserForm is
cancelled, or if the user presses Esc?
Are there any misspellings in the text? Excel's spelling checker doesn't
work with UserForms.
Does the UserForm have an appropriate caption?
If applicable, will your UserForm fit on the screen in lower screen
resolutions?
If your UserForm will be used in multiple versions of Excel, have you
tested the application on all versions?
If you use help, is the help topic correct? And does it explain all the
controls?
82
Excel VBA Introduction – Course Exercise
Exercise 53
Debugging and Error Handling
Errors
When you execute a programme, procedure you may get an incorrect result
or the execution of the code causes a permanent stop. This can be because a
mistake in the code, called a bug or if a statement in the code tries to call an
invalid operation.
Examples of this can be a misspelt variable that will cause an error. When
an error occurs VBA will either display an error message or refer you to the
help file.
VBA provides you with a set of tools for debugging your code these include,
toggle or break points, and the watch window.
Error Types
There are three types of programming error, compile time, run time and
logical. The following table describes the type of error.
Compile Time error
A compile-time error happens when the program is being compiled.
Generally, compile-time errors are syntax errors; and they are caught by
the compiler.
Compile Time error This is because no Endif Present
Sub calculationbonus()
Dim bonus As Currency, earnings As Currency
earnings = InputBox("enter earnings")
If earnings > 40000 Then
bonus = earnings * (12 / 100)
MsgBox "the bonus is " & bonus
End Sub
83
Excel VBA Introduction – Course Exercise
Sub bonus()
Dim bonusamt As Currency, salesamt As Currency
salesamt = 10
bonusamt = salesamt * (6 / 0)
MsgBox "bonus is " & bonusamt
End Sub
Logical Error
84
Excel VBA Introduction – Course Exercise
Exercise 54
Debugging overview
Debugging
To create an error free application you need to be able to trace an correct
errors when they occur, the process is called debugging. VBA provides the
following tools to help you debug your code these are located on the debug
toolbar.
Debugging tools
The following table describes the tools available to you in VBA to view
values of variables and expressions and trace the execution of a program.
Tool Used To
Break Point Pause the execution of code at a specified
statement. You can insert a breakpoint in the
first line of code segment that you suspect to
be the cause of the error. You can then
monitor the execution of the code
Watch Window Monitor values of specified variables and
expressions while the code is running
Immediate Window Test your output by assigning different
values to variables or expressions
Locals Window Monitor all the declared variables of the
procedure currently running
Exercise 55
Debugging
85
Excel VBA Introduction – Course Exercise
when the executed code reaches the breakpoint VBA switches into break
mode. Breakpoints are temporary markers and are not saved along with
the code.
To insert or remove a breakpoint place the insertion point in the code
you want to insert the break point and use one of the following methods.
Choose debug, toggle breakpoint
Press F9
Click the toggle breakpoint button on the debug toolbar ( if not open
remove it.
86
Excel VBA Introduction – Course Exercise
Setting a Breakpoint
Open a new work book and layout the data as shown below
workbook
Mouse Training
Performance Report Excel
salesperson Qtr 1 Qtr 2 Qtr 3 Qtr 4 Total Sales Commission
jackie Whetstone £ 2,500.00 £ 2,750.00 £ 3,000.00 £ 3,250.00 £ 11,500.00
Glenda Eaton £ 3,456.00 £ 3,121.00 £ 1,323.00 £ 4,565.00 £ 12,465.00
Lynda hompson £ 5,676.00 £ 6,754.00 £ 8,765.00 £ 5,674.00 £ 26,869.00
Jane Goodman £ 2,345.00 £ 1,234.00 £ 5,674.00 £ 6,754.00 £ 16,007.00
Sylvia Myres £ 2,500.00 £ 1,234.00 £ 2,345.00 £ 6,754.00 £ 12,833.00
Krystyna Ludlow £ 6,754.00 £ 5,674.00 £ 1,323.00 £ 6,754.00 £ 20,505.00
John Baker £ 1,789.00 £ 2,234.00 £ 1,789.00 £ 6,754.00 £ 12,566.00
Tony Shaw £ 1,314.00 £ 2,500.00 £ 1,789.00 £ 2,234.00 £ 7,837.00
Andy Lee £ 2,234.00 £ 2,345.00 £ 1,323.00 £ 1,234.00 £ 7,136.00
Mary Smith £ 6,754.00 £ 1,234.00 £ 2,500.00 £ 1,323.00 £ 11,811.00
Laura Philips £ 2,345.00 £ 1,234.00 £ 6,754.00 £ 6,754.00 £ 17,087.00
Adam Short £ 2,234.00 £ 6,754.00 £ 1,789.00 £ 1,234.00 £ 12,011.00
Ken Austin £ 1,314.00 £ 1,234.00 £ 2,500.00 £ 2,500.00 £ 7,548.00
Caroline Watson £ 1,789.00 £ 1,314.00 £ 2,500.00 £ 1,323.00 £ 6,926.00
Shaun Roberts £ 2,234.00 £ 6,787.00 £ 1,314.00 £ 2,500.00 £ 12,835.00
87
Excel VBA Introduction – Course Exercise
End Sub
Click the calculate button the code emulates the formula below
=IF(F2<5000,F2*0%,IF(F2<10000,F2*10%,F2*30%))
Click in the column border to set the break point to the left of ElseIf
TotalSales < 10000 Then
Press the F5 or play button to run to break point or press f8 to step through
the code, make sure you have the locals window open, we can monitor the
changes as the code executes.
88
Excel VBA Introduction – Course Exercise
Use shift and F8 to step over code this avoids calling subprocedures
Find the error note the line commisionamnt = TotalSales + 0.3 it should
read commisionamnt = TotalSales * 0.3 multiply not add
Changing the code makes the logic run correctly and the results are correct
logic functions are the hardest to detect
Exercise 56
Watch Expressions
Some errors may not be traceable to a single statement in your code, for
example in some logical errors it’s difficult to isolate the line of code that is
causing the error. In cases such as this you need to monitor the behaviour
the expressions and variables of the entire procedure. Each expression or
variable you monitor is known as a watch, watch expressions can be
defined in either break mode or design time.
Under context specify the procedure and module names for the current
project, this is important when you have variables of the same name but
different scope.
Click ok to display the watch window
89
Excel VBA Introduction – Course Exercise
Consider the following, using the file you have already created make
context region make sure the procedure list refers to commision and the
module list states sheet1 then set watch type to watch expression
Click ok
Now these watches are in place we shall now use stepping through code to
see how they work.
Press the F5 or play button to run to break point or press f8 to step through
the code, make sure you have the locals window open, we can monitor the
changes as the code executes.
90
Excel VBA Introduction – Course Exercise
Exercise 57
The immediate Window
The immediate window helps monitor values assigned to variables and
expressions, change the values of variables and expressions and test the
results of expressions based on these new values. You can use the print
method or use a (?) mark followed by the variable name to view the current
value of a variable.
To view , immediate window click the immediate window on the debug
window.
Option Explicit
Point your cursor art the first procedure as shown note the variable
percentage as 6
91
Excel VBA Introduction – Course Exercise
Point your cursor art the first procedure as shown note the variable
percentage as 15
Press F8 to run the line that calculates the bonus amount and move to
immediate window
Press the Enter Key to display the bonus amount.
92
Excel VBA Introduction – Course Exercise
Exercise 58
Locals Window
The locals window helps you monitor the values of variables within the
current executing procedure or function
The Locals Window
VBA provides one way to access the objects from which Excel is composed.
Start to examine these objects by writing a short routine to change the
value of a variable. Activate the VB Editor, select Insert/Module and enter
the following subroutine in the code window:
Sub SampleVariable()
Dim aval As Variant
aval = 200
aval = 123.123
aval = "Cat"
aval = True
aval = #12/1/1998#
End Sub
Now select the Locals Window command from the View menu and then use
the F8 key to step through the subroutine.
You will see the entries in the Locals Window change as each line is
executed with the contents and type of each variable displayed in turn.
93
Excel VBA Introduction – Course Exercise
Exercise 59
Error handling
The goal of well-designed error handling code is to anticipate potential
errors, and correct them at run time or to terminate code execution in a
controlled, graceful method. Your goal should be to prevent unhandled
errors from arising.
Below we show one example
Sub errortest()
' the reason for the error is there is no sheet called new sheet
Exit Sub
'if you un-comment on go to error the following error handler will
create a new sheet
ErrHandler:
If Err.Number = 9 Then
' sheet does not exist, so create it
Worksheets.Add.Name = "NewSheet"
' go back to the line of code that caused the problem
Resume
End If
End Sub
A Note Of Caution
94
Excel VBA Introduction – Course Exercise
Code Examples
Used range of cells - worksheet protection by value type
This sub procedure looks at every cell on the active worksheet and if the
cell does not have a formula, a date or text and the cell is numeric; it
unlocks the cell and makes the font blue.
For everything else, it locks the cell and makes the font black. It then
protects the worksheet.
This has the effect of allowing someone to edit the numbers but they
cannot change the text, dates or formulas.
Sub SetProtection()
On Error GoTo errorHandler
errorHandler:
MsgBox "Error"
End Sub
95
Excel VBA Introduction – Course Exercise
Sub SumRange()
Dim i As Integer
Dim cel As Range
Set cel = ActiveCell
For i = 1 To 10
cel(i).Value = 100
Next i
cel(i).Value = "=SUM(R[-10]C:R[-1]C)"
End Sub
Other functions can be used as well as changing the range and values to
suit.
96
Excel VBA Introduction – Course Exercise
Sub ToggleValues()
Dim rowIndex As Integer
Dim colIndex As Integer
For rowIndex = 1 To 10
For colIndex = 1 To 5
If Cells(rowIndex, colIndex).Value = "X" Then
Cells(rowIndex, colIndex).Value = "O"
Else
Cells(rowIndex, colIndex).Value = "X"
End If
Next colIndex
Next rowIndex
End Sub
Sub SetValuesAllSheets()
Dim wSht As Worksheet
Dim myRng As Range
Dim allwShts As Sheets
Dim cel As Range
97
Excel VBA Introduction – Course Exercise
Sub HideSheet()
Worksheets(2).Visible = Hide 'you can use Hide or False
End Sub
Sub VeryHiddenSheet()
Worksheets(2).Visible = xlVeryHidden 'menu item is not available
End Sub
Sub UnHideSheet()
Worksheets(2).Visible = True
End Sub
To toggle between hidden and visible
Sub ToggleHiddenVisible()
Worksheets(2).Visible = Not Worksheets(2).Visible
End Sub
98
Excel VBA Introduction – Course Exercise
Toggle opposite visibility (error will happen as all worksheets cannot be hidden, at
least one must be visible in a workbook).
Sub ToggleAllSheets()
On Error Goto errorHandler
Dim wSh As Worksheet
End Sub
Sub UnHideAll()
Dim wSh As Worksheet
99
Excel VBA Introduction – Course Exercise
Checks to see if sheet already exists with the name ‘MySheet’ and does not add it
again as Excel cannot store duplicate worksheet names in a workbook.
Sub AddUniqueSheet()
Dim ws As Worksheet
Dim newSheetName As String
Adds new worksheet with the month and year as its name and sets the range("A1:A5")
from Sheet1 to new worksheet.
This can only be executed once for the same period due to excel not allowing
duplicate worksheets names.
Make sure you have a worksheet called ‘Sheet1’ and that its range ‘A1:A5’ has some
content which to copy across.
Sub AddSheet()
Dim wSht As Worksheet
Dim shtName As String
100
Excel VBA Introduction – Course Exercise
End If
Next wSht
Sheets.Add.Name = shtName
Sheets(shtName).Move After:=Sheets(Sheets.Count)
Sheets("Sheet1").Range("A1:A5").Copy _
Sheets(shtName).Range("C1") 'range("C1") = starting point
End Sub
Copies the contents of the first positioned worksheet to a new worksheet (‘NewSheet’)
validating if sheet exists first.
Sub CopySheet()
Dim wSht As Worksheet
Dim shtName As String
Next wSht
Sheets(1).Copy Before:=Sheets(1)
Sheets(1).Name = shtName
Sheets(shtName).Move After:=Sheets(Sheets.Count)
End Sub
Index number for a sheet can be used instead of the actual string name. This is useful if
name is not known or you want to control the order position of the sheet in question.
Back to top
Sub CalcPay()
On Error GoTo HandleError
Dim hours
Dim hourlyPay
Dim payPerWeek
101
Excel VBA Introduction – Course Exercise
hourlyPay = InputBox("Please enter hourly pay", "Pay Rate")
payPerWeek = CCur(hours * hourlyPay)
MsgBox "Pay is: " & Format(payPerWeek, "£##,##0.00"), , "Total Pay"
HandleError: 'any error - gracefully end
End Sub
No communication with Excel is required for this example and can be started from within
the VB Editor.
To split a single line of execution into multiple lines, use the underscore character ( _ ).
What impact will this have if you use the integer function (Int()) instead of the currency
functions (CCur)?
Other functions: CDbl (double) and CSng (single).
Date Entry & Formula with InputBox which prompts the user for the number of times
to iterate, creates heading and calculates gross values with final totals at the
end of the columns.
Sub ProcessTransactions()
ActiveCell.Value = "NET"
ActiveCell.Offset(0, 1).Value =
"GROSS" ActiveCell.Offset(1, 0).Select
With Selection.Borders(xlEdgeTop)
.LineStyle = xlContinuous
.Weight = xlThin
.ColorIndex = xlAutomatic
End With
With Selection.Borders(xlEdgeBottom)
.LineStyle = xlDouble
102
Excel VBA Introduction – Course Exercise
.Weight = xlThick
.ColorIndex = xlAutomatic
End With
End Sub
The above is A For Next Example with InputBox Function, With Block and Offset
method
Back to top
Printing examples
Sub PrintReport1()
Sheets(1).PageSetup.Orientation = xlLandscape
Range("Report").PrintOut Copies:=1
End Sub
Sub PrintReport2()
Range("HVIII_3A2").PrintOut
Range("BVIII_3").PrintOut
Range("BVIII_4A").PrintOut
Range("HVIII_4A2").PrintOut
Range("BVIII_5A").PrintOut
Range("BVIII_5B2").PrintOut
Range("HVIII_5A2").PrintOut
Range("HVIII_5B2").PrintOut
End Sub
To print a defined area, centre horizontally, with 2 rows as titles, in portrait orientation and
fitted to page wide and tall - 1 copy.
Sub PrintReport3()
With Worksheets("Sheet1")
.PageSetup
.CenterHorizontally = True
103
Excel VBA Introduction – Course Exercise
.PrintArea = "$A$3:$F$15"
.PrintTitleRows = ("$A$1:$A$2")
.Orientation = xlPortrait
.FitToPagesWide = 1
.FitToPagesTall = 1
End With
Worksheets("Sheet1").PrintOut
End Sub
To print preview, control the font and to pull second line of header (“A1”) from first worksheet.
Sub PrintHeaderPreview()
ActiveSheet.PageSetup.CenterHeader = "&""Arial,Bold Italic""&14 _
My Report" & Chr(13) & Sheets(1).Range("A1")
ActiveWindow.SelectedSheets.PrintPreview
End Sub
Back to top
Sub GetSum()
[A1].Value = Application.Sum([E1:E15])
End Sub
Other functions - AVERAGE, MIN, MAX, COUNT, COUNTBLANK, COUNTA, VLOOUKP etc…
Sub EnableEventReset()
Application.EnableEvents = True
End Sub
104
Excel VBA Introduction – Course Exercise
To display the full path and filename of the current workbook (Function)
Sub FormatHeader()
With ThisWorkbook
.Worksheets("MySheet").PageSetup.LeftHeader = .FullName
End With
End Sub
Sub Set_FKeys()
Application.OnKey "{F3}", "MySub"
End Sub
Sub Restore_FKeys()
Application.OnKey "{F3}"
End Sub
Cursors
Sub ShowHourGlass()
Application.Cursor = xlWait
End Sub
105
Excel VBA Introduction – Course Exercise
Sub ResetCursor()
Application.Cursor = xlNormal
End Sub
With ActiveWindow
.DisplayGridlines = Not .DisplayGridlines
.DisplayHeadings = Not .DisplayHeadings
.DisplayHorizontalScrollBar = Not .DisplayHorizontalScrollBar
.DisplayVerticalScrollBar = Not .DisplayVerticalScrollBar
.DisplayWorkbookTabs = Not .DisplayWorkbookTabs
End With
With ActiveWindow
.DisplayFormulaBar = Not .DisplayFormulaBar
.DisplayStatusBar = Not .DisplayStatusBar
End With
Sub ActiveCellInRange()
Range("A11:D15").Select
Selection.Offset(1, 1).Activate
End Sub
Back to top
106
Excel VBA Introduction – Course Exercise
Sub AddName1()
ActiveSheet.Names.Add Name:="MyRange1", RefersTo:="=$A$1:$B$10"
End Sub
Sub AddName2()
ActiveSheet.Names.Add Name:="MyRange2", RefersTo:="=" & _
Selection.Address()
End Sub
Sub AddName3()
Dim rng As String
rng = Selection.Address
ActiveSheet.Names.Add Name:="MyRange3", RefersTo:="=" & rng
End Sub
Sub AddName4()
Selection.Name = "MyRange4"
End Sub
Sub DeleteAllRanges()
Dim rName As Name
107
Excel VBA Introduction – Course Exercise
For Each rName In ActiveWorkbook.Names
rName.Delete
Next rName
End Sub
Sub ScreeTopLeft()
ActiveCell.Select
With ActiveWindow
.ScrollColumn = ActiveCell.Column
.ScrollRow = ActiveCell.Row
End With
End Sub
With ws
'Find the last row
LastRow = .Cells.Find(What:="*", _
SearchDirection:=xlPrevious, _
SearchOrder:=xlByRows).Row
'Find the last column
LastCol = .Cells.Find(What:="*", _
SearchDirection:=xlPrevious, _
SearchOrder:=xlByColumns).Column
End With
'Finally, initialize a Range object variable for
'the last populated row.
Sub ShowLastCell()
MsgBox LastCell(Sheet1).Address(False, False)
End Sub
108
Excel VBA Introduction – Course Exercise
Try MsgBox LastCell(Sheet1).Row
Sub CheckRange()
Dim rng As Range
Sub MyCount()
Dim myCount As Long
myCount = Selection.Rows.Count
MsgBox myCount
End Sub
Sub MySheetCount()
Dim myCount As Long
myCount = Application.Sheets.Count
MsgBox myCount
End Sub
Sub CopyRange1()
Range("A1:A3").Copy Destination:=ActiveCell
End Sub
109
Excel VBA Introduction – Course Exercise
Sub CopyRange2()
Sheets("sheet3").Range("A1:A3").Copy Destination:=ActiveCell
End Sub
Sub MyPosition()
Dim myRpw, myCol
myRow = ActiveCell.Row
myCol = ActiveCell.Column
MsgBox myRow & "," & myCol
End Sub
Range(“A1”) Cell A1
[A1] Cell A1
Cell(1) Cell A1
Range(“A:A”) Column A
[A:A] Column A
Range(“5:5”) Row 5
[5:5] Row 5
110
Excel VBA Introduction – Course Exercise
Back to top
Sub MoveDown()
ActiveCell.Offset(1, 0).Select
End Sub
Sub MoveUp()
ActiveCell.Offset(-1, 0).Select
End Sub
Sub MoveRight()
ActiveCell.Offset(0, 1).Select
End Sub
Sub DownLeft()
ActiveCell.Offset(0, -1).Select
111
Excel VBA Introduction – Course Exercise
End Sub
Sub LastCellInRange()
Range(ActiveCell.Address).End(xlDown).Select
Range(ActiveCell.Address).End(xlToRight).Select
End Sub
Back to top
Use the Private keyword, which is local and invisible via Excel application.
112
Excel VBA Introduction – Course Exercise
Sub ListFiles()
ReadFiles "c:\winnt"
End Sub
113
Excel VBA Introduction – Course Exercise
Function TotalValue(Qty As Double, UPrice As Double) As Double
TotalValue = Format((Qty * UPrice * 1.175), "£#,##0.00")
End Function
Age (simple)
Function Age2(DOB)
Age2 = Int((Now() - DOB) / 365.25) & " Years old"
End Function
Age (alternative)
Function Age(DOB)
If Month(DOB) > Month(Now) Then
Age = Year(Now) - Year(DOB) - 1
ElseIf Month(DOB) < Month(Now) Then
Age = Year(Now) - Year(DOB)
ElseIf Day(DOB) <= Day(Now) Then
Age = Year(Now) - Year(DOB)
Else
Age = Year(Now) - Year(DOB) - 1
End If
End Function
Returns the cell in range which is underline (single style) or the word “unknown”
'Assume Unknown
sResult = "Unknown"
'Return Results
GetUnderlinedCell = sResult
End Function
114
Excel VBA Introduction – Course Exercise
Sub LookupExample()
Dim strMonth As String
Dim bytCurMonth As Byte
bytCurMonth = Month(Date)
strMonth = Choose(bytCurMonth, "Jan", "Feb", "Mar", "Apr", _
"May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec")
MsgBox "Current month is " & strMonth
End Sub
Creates a new word document and populates the contents of cell “B1” along with
some basic formatting.
You need create a reference to the Word Object Library (8.0/9.0/10.0/11.0) in the VB
Editor
Sub CreateMSWordDoc()
On Error GoTo errorHandler
With wdApp
.Visible = True
.WindowState = wdWindowStateMaximize
End With
With mywdRange
.Text = Range("B1") & vbNewLine & "This above text is _
stored in cell 'B1'."
.Font.Name = "Comic Sans MS"
.Font.Size = 12
.Font.ColorIndex = wdGreen
.Bold = True
End With
115
Excel VBA Introduction – Course Exercise
errorHandler:
Set wdApp = Nothing
Set myDoc = Nothing
Set mywdRange = Nothing
End Sub
VBA Websites
116