0% found this document useful (0 votes)
14 views47 pages

ADS211E Unit 2 - Chapter 3 Slides

The document provides an overview of using Visual Basic for Applications (VBA) in Microsoft Excel, focusing on advanced topics such as events, procedures, variables, and functions. It covers how to respond to events, create and call procedures and functions, and manage public and private variables. Additionally, it discusses advanced cell referencing techniques and methods for manipulating rows and columns in Excel using VBA.

Uploaded by

nomcebomnisi02
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views47 pages

ADS211E Unit 2 - Chapter 3 Slides

The document provides an overview of using Visual Basic for Applications (VBA) in Microsoft Excel, focusing on advanced topics such as events, procedures, variables, and functions. It covers how to respond to events, create and call procedures and functions, and manage public and private variables. Additionally, it discusses advanced cell referencing techniques and methods for manipulating rows and columns in Excel using VBA.

Uploaded by

nomcebomnisi02
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 47

PROBLEM SOLVING

USING VBA IN MICROSOFT


EXCEL
USING VISUAL BASIC FOR APPLICATIONS (VBA) IN EXCEL
-
ADVANCED TOPICS

By Thayne Breetzke (University of Fort Hare)


LEARNING OBJECTIVES
• To understand what events are and how to write VBA code to respond to
them.
• To understand what functions are and how to create and use them in VBA.
• To understand the difference between public and private variables,
procedures and functions and when to use them in VBA.
• To be able to call procedures and functions in VBA.
• To be able to pass variables and values to procedures and functions in VBA.
• To be able to use advanced cell referencing techniques in VBA.
• To be able to use various Worksheet methods and properties in VBA.
• To be able to write basic VBA code to solve a problem in Excel.
• To understand how the output seen in Excel results from the VBA code that
was written to produce that output.
EVENTS
• An event is an action that can trigger other code to run.
• Examples of events include:
• A change to a specific worksheet
• Activating a worksheet
• Opening a workbook
• Saving a workbook
• Closing a workbook
EVENTS:
WORKSHEET EVENTS
• Worksheet-level events include:
• Changes to a worksheet
• Activating a worksheet
• Deactivating a worksheet

• To create a worksheet-level event, place your


VBA code in the appropriate worksheet module.
• Double click the desired worksheet module in the
explorer panel on the top-left to open it:
EVENTS:
WORKSHEET EVENTS
• One of the most popular worksheet-level events is the Worksheet_Change
event.
• It runs whenever there is a change to the worksheet.
• To create a sub procedure for this event, follow these steps:
1. Once you have double-clicked on the desired worksheet module, the code window for
that worksheet opens. Select “Worksheet” from the list box on the top-left and the
desired event from the list box next to it.
2. Select “Change” from the list on the right because you are creating a sub procedure for
the worksheet’s Change event. An empty sub procedure is automatically created for you,
as shown below:
EVENTS:
WORKSHEET EVENTS
• To create a sub procedure for this event, follow these steps (continued):
3. Add the VBA code to be executed when the worksheet changes. Note that Target (known
as a parameter) is the range that was changed. You can refer to it in your code. Here’s
an example:

Sub Worksheet_Change(ByVal Target As Range)


’Displays the row number where the changes occurred
MsgBox Target.Row
End Sub
EVENTS:
WORKBOOK EVENTS
• These events are triggered for actions such as
saving, opening, closing the workbook.
• Workbook-level events must be placed in the
ThisWorkbook module.
• Here’s an example of a sub procedure for the
Workbook’s BeforeClose event:

Sub Workbook_BeforeClose(Cancel as Boolean)


MsgBox “Closing”
End Sub
EVENTS:
BUTTON EVENTS
• You can add a button object (called a control) to an Excel spreadsheet and
have it execute VBA code when it is clicked. To add a button, do the
following:
1. On the Developer tab, click the Insert command button.
2. Click the top-left icon (a button) from the options that appear.
3. Draw a button on your spreadsheet where you want it by holding down the left mouse
button and dragging the mouse to select the desired size of the button.
4. You need to provide a name for the sub procedure that will be called when the button is
clicked. Enter a short, descriptive name for the button followed by “_Click”, for example:
MyButton_Click
5. From the Macros in list box, select the file name of your spreadsheet.
6. Click the New button. Notice that an empty sub procedure has been created for you in
the VBA code editor window. This is the sub procedure (or macro) that will handle the
click of the button.
EVENTS:
BUTTON EVENTS
• Here is an example of an empty sub procedure that might be created for a
button:

Sub MyButton_Click()

End Sub

• You simply need to add the needed VBA code to the sub procedure to have
the code execute when the button is clicked.
• Note that you can press Alt-Tab to flip between your Excel spreadsheet and
the VBA code editor window.
ADVANCED PROCEDURES, VARIABLES AND
FUNCTIONS
• We now cover various options that are available to you as your code
becomes more complex.
ADVANCED PROCEDURES, VARIABLES AND FUNCTIONS:
CALLING PROCEDURES
• When you first start coding, you will probably create a single sub procedure
that completes an entire task.
• When your code becomes long, you should split it up into multiple
procedures to make it more easily manageable (called modularizing your
code).
• Each procedure should take care of a specific sub-task of the overall task.
• You can then call each procedure from within your main procedure.
• Creating the procedure once and calling it as many times as you need to promotes code
reuse by reducing unnecessary duplication of code.
ADVANCED PROCEDURES, VARIABLES AND FUNCTIONS:
CALLING PROCEDURES
• Here’s an example of calling procedures:
Sub MyMainSub()
’Main sub procedure to co-ordinate the sub-tasks
Call MySub1
Call MySub2
End Sub

Sub MySub1()
’Does a specific sub-task
End Sub

Sub MySub2()
’Does a specific sub-task
End Sub
ADVANCED PROCEDURES, VARIABLES AND FUNCTIONS:
PUBLIC VARIABLES
• You have already seen how to declare variables inside a sub procedure and
function by using the Dim keyword.
• A variable declared within a sub procedure/function can’t be used outside
of that procedure/function.
• If you need to use the same variable in multiple procedures or functions,
you can declare it as a public variable:
• Place the word “Public” at the beginning of the declaration statement, and
• Move the statement to outside of the procedure/function (to the top of the module).
• Thus, the value of the public variable can be accessed and changed from
multiple procedures/functions.
ADVANCED PROCEDURES, VARIABLES AND FUNCTIONS:
PUBLIC VARIABLES
• The following example declares one public variable. Two sub procedures
access and change the variable’s value.
Public text as String

Sub MySub1()
’Modifies the public variable named text
text = “In MySub1”
End Sub

Sub MySub2()
’Modifies the public variable named text
text = “In MySub2”
End Sub
ADVANCED PROCEDURES, VARIABLES AND FUNCTIONS:
PASSING VARIABLES/VALUES
• As an alternative to using public variables, you can pass variables or values
from one procedure to another.
• First, prepare your procedure to accept the variables or values. In
programming terms, this is called defining parameters for the procedure.

Sub MySub1(score as Long, msg as String)


’Modifies the public variable named text
MsgBox “Your score is “ & score, vbOKOnly, msg
End Sub

• The parameters define what values will be passed to the procedure when
another procedure calls it. In the above example, the procedure can
accept a number followed by a string as inputs when the procedure is
called.
ADVANCED PROCEDURES, VARIABLES AND FUNCTIONS:
PASSING VARIABLES/VALUES
Sub MySub1(score as Long, msg as String)
’Modifies the public variable named text
MsgBox “Your score is “ & score, vbOKOnly, msg
End Sub

• In programming terms, we say that we pass arguments to a procedure.


The arguments are received by the procedure’s parameters. Here’s how
the procedure above can be called:

Sub MyMainSub()
’Calls procedure MySub1, passing it 75 and “Well done!” as inputs.
Call MySub1(75, “Well done!”)
End Sub
ADVANCED PROCEDURES, VARIABLES AND FUNCTIONS:
FUNCTIONS
• Functions are similar to sub procedures with two main differences:
• Functions return a value.
• Functions can be used in Excel just like Excel’s built in functions (e.g., vLookup).

• As with procedures, creating a function allows you to call it from multiple


places in your code even though it is defined only once.
• This eliminates unnecessary duplication of code.
ADVANCED PROCEDURES, VARIABLES AND FUNCTIONS:
FUNCTIONS
• You create functions in a similar way to creating sub procedures, except
you define a type of the result to be returned by it.

Function MaxValue(num1 as Long, num2 as Long) as Long


’Returns the bigger of the two numbers passed to the function.
If num1 > num2 Then
MaxValue = num1
Else
MaxValue = num2
End If
End Function

• “As Long” at the end of the first line above means that this function will return a result
that is of the Long data type.
• The function must assign a value to the name of the function to have that value be passed
back as the result of the function.
ADVANCED PROCEDURES, VARIABLES AND FUNCTIONS:
FUNCTIONS
Function MaxValue(num1 as Long, num2 as Long) as Long
’Returns the bigger of the two numbers passed to the function.
If num1 > num2 Then
MaxValue = num1
Else
MaxValue = num2
End If
End Function

• Here’s how we might call the function above:


Sub MySub()
Dim num as Long

’Calls function MaxValue, passing it 10 and 12 as inputs, and stores


’the result (12) in variable num.
num = MaxValue(10, 12)
End Sub
ADVANCED PROCEDURES, VARIABLES AND FUNCTIONS:
FUNCTIONS
Sub MySub()
Dim num as Long

’Calls function MaxValue, passing it 10 and 12 as inputs, and stores


’the result (12) in variable num.
num = MaxValue(10, 12)
End Sub

• Notice that the code that calls the function must “consume” the result in
some way (e.g., display it or store it in a variable).
• Functions are particularly useful in that you can also call them directly from
your worksheet.
• For example, you could call the MaxValue function from your spreadsheet by typing the
following in a cell:
=MaxValue(15, 9)
ADVANCED PROCEDURES, VARIABLES AND FUNCTIONS:
PRIVATE VS PUBLIC
• Public variables are variables that may be accessed and changed from
anywhere.
• By default, all procedures and functions are considered “Public”.
• You can create private variables, procedures and functions.
• These can only be used within the module where they reside.

• To declare a private (module-level) variable, declare it at the top of the


module and use the Private keyword.

Private num as Long

Sub MySub()
End Sub
ADVANCED PROCEDURES, VARIABLES AND FUNCTIONS:
PRIVATE VS PUBLIC
• To make a procedure or function private, just add “Private” to the beginning
of the definition.

Private Sub MySub1(score as Long, msg as String)


’Modifies the public variable named text
MsgBox “Your score is “ & score, vbOKOnly, msg
End Sub

Private Function MaxValue(num1 as Long, num2 as Long) as Long


’Returns the bigger of the two numbers passed to the function.
If num1 > num2 Then
MaxValue = num1
Else
MaxValue = num2
End If
End Function
ADVANCED CELL REFERENCING
• You have already seen the basics of using VBA to interact with cells, sheets,
and workbooks.
• This section explores some advanced techniques for interacting with rows,
columns, etc.
ADVANCED CELL REFERENCING:
ROWS AND COLUMNS
• You can get the row or column number of a cell like this:
Sub MySub()
Dim row as Long
Dim col as Long

row = Range(“A3”).Row ’Variable row gets the value 3


col = Range(“A3”).Column ’Variable col gets the value 1
End Sub
ADVANCED CELL REFERENCING:
Rows AND Columns OBJECTS
• The Rows and Columns objects return a Range object.
• The Range object represents all the rows/columns on the specified worksheet.

• Use the Insert and Delete methods to insert and delete rows and columns.
Sub MySub()
’This deletes row 3 on Sheet 1
Worksheets(“Sheet1”).Rows(3).Delete
’This inserts a row after row 3 on Sheet 1
Worksheets(“Sheet1”).Rows(4).Insert
’This deletes column 2 on Sheet 1
Worksheets(“Sheet1”).Columns(2).Delete
’This inserts a column after column 2 on Sheet 1
Worksheets(“Sheet1”).Columns(3).Insert
’This deletes column B on Sheet 1
Worksheets(“Sheet1”).Columns(“B”).Delete
’This inserts a column after column B on Sheet 1
Worksheets(“Sheet1”).Columns(“C”).Insert
End Sub
ADVANCED CELL REFERENCING:
REFERENCING ROWS AND COLUMNS USING
THE Range OBJECT
• Alternatively, you can refer to entire columns and rows by adding
“.EntireColumn” or “.EntireRow” after referring to a Range object.

Sub MySub()
’This inserts a column to the right of range “B2”
Range(“B3”).EntireColumn.Insert

’This inserts a row below range “C4”


Range(“C5”).EntireRow.Insert
End Sub
ADVANCED CELL REFERENCING:
HIDING AND UNHIDING ROWS AND
COLUMNS
• Rows and columns have the Hidden property that is set to either True or
False to hide or unhide them.
Sub MySub()
’This hides row 1 on Sheet 1
Worksheets(“Sheet1”).Rows(1).Hidden = True

’This also hides row 1 on Sheet 1


Range(“A1”).EntireRow.Hidden = True

’This hides column C on Sheet 1


Worksheets(“Sheet1”).Columns(“C”).Hidden = True

’This unhides columns B and C on Sheet 1


Range(“B:C”).EntireRow.Hidden = False
End Sub
ADVANCED CELL REFERENCING:
THE Count METHOD
• The Count method is used to count the number of cells, columns or rows in
a range.

Sub MySub()
Dim count as Long

’Variable count gets the value 3


count = Range(“A1:A3”).Count

’Variable count gets the value 10


count = Range(“A1:A10”).Rows.Count
End Sub
ADVANCED CELL REFERENCING:
COPY, PASTE, AND PASTE SPECIAL
• Use the Copy method to copy a range and paste it elsewhere.
• The Paste Special method allows certain properties of cells (e.g., only cell
values) to be pasted instead of all cell properties.
• Specify the desired value for the Paste parameter to modify the type of
paste.
Sub MySub()
’Copy cell A1 to cell B1
Range(“A1”).Copy Range(“B1”)

’Copy cell A1 and paste only the formats to B1


Range(“A1”).Copy
Range(“B1”).PasteSpecial Paste:=xlPasteFormats
End Sub
ADVANCED CELL REFERENCING:
COPY, PASTE, AND PASTE SPECIAL
• Commonly used values for the Paste parameter are:
Name Description
xlPasteAll Everything will be pasted
xlPasteAllExceptBorders Everything except borders will be
pasted.
xlPasteAllMergingConditionalFor Everything will be pasted and
mats conditional formats will be merged.
xlPasteColumnWidths Copied column width is pasted.
xlPasteFormats Copied source format is pasted.
xlPasteFormulas Formulas are pasted.
xlPasteFormulasAndNumberFor Formulas and number formats are
mats pasted.
xlPasteValues Values are pasted.
xlPasteValuesAndNumberFormat Values and number formats are
ADVANCED CELL REFERENCING:
R1C1 CELL-REFERENCING AND THE Cells
OBJECT
• When referencing cells by using the Range object, you can refer to the
cells’ column letters and row numbers.
• This is called A1-style cell referencing.
• Instead, you can refer to the column number instead of its letter.
• This is called R1C1-style referencing,

Sub MySub()
’Uses A1-style referencing to refer to cell B3
Range(“B3”).Value = 5

’Uses R1C1-style referencing to refer to cell B3


Range(“R3C2”).Value = 5
End Sub
ADVANCED CELL REFERENCING:
R1C1 CELL-REFERENCING AND THE Cells
OBJECT
• The Cells object also allows another way to refer to cells using column and
row numbers:
Sub MySub()
’Using the Cells object to refer to cell B3. Specify the row number
’first and then the column number.
Cells(3,2).Value = 5
End Sub
ADVANCED CELL REFERENCING:
FINDING THE LAST ROW OR LAST COLUMN
• Excel keeps a record of the last used cell in each worksheet.
• The UsedRange property returns a Range object that represents the used
range on the worksheet.
Sub MySub()
Dim lastRow as Long
Dim lastCol as Long

’Returns the last used row in the active worksheet and assigns it to
’variable lastRow
lastRow = ActiveSheet.UsedRange.Row

’Returns the last used column in the active worksheet and assigns it
’to variable lastRow
lastCol = ActiveSheet.UsedRange.Column
End Sub
ADVANCED CELL REFERENCING:
FINDING THE LAST ROW OR LAST COLUMN
• Be careful when using the UsedRange property as it won't always provide
the answer that you expect because:
• UsedRange only recalculates when the workbook is saved.
• If you delete rows, columns, or data you will need to save the workbook before those changes are
reflected by the UsedRange property.

• The UsedRange property can count formatting.


• Even if a cell value is blank, if the cell is formatted it will count in the used range.
• Therefore, make sure to use the Clear method instead of the ClearContents method if you want
to remove cells from the used range.
• You could also delete entire rows or columns.
ADVANCED CELL REFERENCING:
FINDING THE LAST ROW OR LAST COLUMN
• If you want to find the last used cell in a particular row or column, you need
to use the End method.
Sub MySub()
Dim last as Long

’Starts searching from the bottom of the worksheet for the last used
’cell in the first column. Returns the row number.
’Rows.Count returns the number of rows in the worksheet
last = ActiveSheet.Cells(ActiveSheet.Rows.Count, 1).End(xlUp).Row

’Starts searching from the rightmost side of the worksheet for the
’last used cell in the first row. Returns the column number.
’Columns.Count returns the number of columns in the worksheet
last = ActiveSheet.Cells(1,ActiveSheet.Columns.Count).End(xlToLeft).Column
End Sub
ADVANCED CELL REFERENCING:
Offset AND Resize
• The Offset property allows you to offset a cell range by a number of rows or
columns.

Sub MySub()
’Selects cell B3 (2 cells down, and 1 to the right of cell A1)
Range(“A1”).Offset(2,1).Select

’Selects cell B2 (3 cells up, and 2 to the left of cell D5)


Range(“D5”).Offset(-3,-2).Select
End Sub
ADVANCED CELL REFERENCING:
Offset AND Resize
• The Resize property allows you to resize the specified range.
Sub MySub()
Dim numRows as Long
Dim numColumns as Long

’Resizes the selection on Sheet1 to extend it by one row and one column
Worksheets(“Sheet1”).Activate
numRows = Selection.Rows.Count
numColumns = Selection.Columns.Count
Selection.Resize(numRows + 1, numColumns + 1).Select
End Sub
ADVANCED CELL REFERENCING:
THE FormulaR1C1 PROPERTY
• You are already familiar with the Formula property for assigning a formula
to a cell.
• When the formula uses R1C1-style notation for referring to cells, use the
FormulaR1C1 property instead.

Sub MySub()
’Sets the formula for range B1:B10 to equal cell C8, using R1C1-
’style notation. Cells B1 to B10 get the formula “=R8C3”.
Range(“B1:B10”).FormulaR1C1 = “=R8C3”

’Sets the formula for cell B2 to calculate the square root of cell
’A2. Cell B2 is row 2 of column 2.
Range(“B2”).FormulaR1C1 = “=SQRT(R2C1)”
End Sub
ADVANCED CELL REFERENCING:
THE FormulaR1C1 PROPERTY
• Enclose the numbers in the R1C1-style formula in square brackets if you
want to use relative cell referencing.
• In other words, you indicate how many rows/columns to offset from the
current cell.

Sub MySub()
’Sets the formula for range B1:B10 to the first column to the right
’of the cell containing the formula. No number after “R” means that
’VBA will look at the same row.
Range(“B1:B10”).FormulaR1C1 = “=RC[1]”

’Sets the formula for range B1:B10 to the first column to the left
’of the cell containing the formula. No number after “R” means that
’VBA will look at the same row.
Range(“B1:B10”).FormulaR1C1 = “=RC[-1]”
End Sub
ADVANCED CELL REFERENCING:
ActiveCell
• ActiveCell references the currently active cell.
Sub MySub()
’Selects the cell one column to the right of the active cell
ActiveCell.Offset(0,1).Select
End Sub
WORKSHEETS
• You’ve mostly used the Worksheets object to identify which sheet to work
with.
• Now you will learn about the Worksheet methods and properties.
WORKSHEETS:
CHANGING A WORKSHEET’S NAME
• You can easily change a worksheet’s name:
Sub MySub()
’Changes the worksheet’s name
Worksheets(“Sheet1”).Name = “OldSheet1”
End Sub
WORKSHEETS:
HIDING AND UNHIDING SHEETS
• Hide and unhide worksheets by setting its Visible property.
Sub MySub()
’Hides the worksheet named Sheet1
Worksheets(“Sheet1”).Visible = False

’Unhides the worksheet named Sheet1


Worksheets(“Sheet1”).Visible = True
End Sub

• To make a worksheet hidden so that it can only be unhidden using VBA, set
the visible property to xlSheetVeryHidden.
• The worksheet will not be able to be unhidden from within Excel.
WORKSHEETS:
PROTECTING AND UNPROTECTING
WORKSHEETS
• Worksheets can be password protected so that they cannot be modified.
• If you password-protect a worksheet:
• You will need your code to unprotect the worksheet before it can make changes to any
protected properties,
• You will need to re-protect it once the code finishes running.

• Refer to the Microsoft VBA documentation for various other protection


parameters that you can use.

Sub MySub()
’Protects the worksheet with a password
Worksheets(“Sheet1”).Protect “SecretPassword”

’Unprotects the worksheet with a password


Worksheets(“Sheet1”).Unprotect “SecretPassword”
End Sub
These slides are based on the online tutorial entitled Learn
VBA Online – Tutorial for Beginners, available at:

https://www.automateexcel.com/learn-vba-tutorial/

You might also like