ADS211E Unit 2 - Chapter 3 Slides
ADS211E Unit 2 - Chapter 3 Slides
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.
• 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
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 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
• 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.
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.
• 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
Sub MySub()
Dim count as Long
Sub MySub()
’Uses A1-style referencing to refer to cell B3
Range(“B3”).Value = 5
’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.
’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
’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
• 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.
Sub MySub()
’Protects the worksheet with a password
Worksheets(“Sheet1”).Protect “SecretPassword”
https://www.automateexcel.com/learn-vba-tutorial/