SlideShare a Scribd company logo
LECTURE 9

Range objects
User-Defined
Functions
SUMMARY
Range objects
Obtaining a range using the RefEdit control
User-Defined Functions
 Without arguments

 With arguments
 Variables, constants, arrays and range objects
RANGE OBJECTS

A cross
between a
named range
and an array
RANGE OBJECTS
Range objects are an alternative to using arrays
and named ranges.

Range objects are preferred when:
 You are using the RefEdit control to allow users to select
data for a program.
 You are creating user defined functions which you want to
use within Excel worksheets (as opposed to using them
solely within your code).
 You are creating an Excel add-in and don’t want to clog up
the user’s workbook with range names.
DECLARING A RANGE OBJECT
A Range is a data type. So we declare a range
object as:
Dim rangeObj as Range
 Where rangeObj is the name you want to assign to the
range object

Assign a range object a range within a procedure:
Set rangeObj = Range

Set rangeObj = Range(“RangeName”)

 Where Range is a range in Excel and RangeName is a
named range in Excel.

 For example,
Set stockRange = Range(Cells(1,1), Cells(1,25))
Set stockRange = Range(“StockPrices”)
METHODS APPLIED TO RANGE OJBECTS
You can do nearly everything the same as a range
or named range in Excel. For example:
 Count rows or columns
rangeObj.Rows.Count

rangeObj.Columns.Count

 Refer to cells within the range
rangeObj.Cells(i, j).Value
REFEDIT CONTROL

Letting the
user select
the range of
data
REFEDIT
RefEdit is a UserForm control:

Allows user to select a range in Excel
Set this selection as a range object in your code
Set rangeObj = Range(RefEdit.Value)

 Where RefEdit is the (Name) of the control

Then use the range however you need to
 In a built-in function
 In a user defined function
 In place of a named range
EXERCISE 1. REFEDIT
Open Lecture 9 Student Example.xlsm
Open UserForm2
In the sub for the command button code the
following:
 Declare a range object called userSelect
 Set this range object equal to the value of the RefEdit
control
 Test that the works by outputting the range object to some
cells
 Use the .Columns.Count and .Rows.Count property to assist you
 Start the output in Cells(1,6) of Sheet 1
 Remember, to ‘copy’ or ‘output’ you just need to set the two
ranges equal to each other
 (make sure to put .Value at the end of each range)
USER DEFINED
FUNCTIONS

Create a
function in
VBA
WHAT IS A USER DEFINED FUNCTION?
Designed/created by YOU, the USER
 Similar to an Excel built-in function

Returns a value: number, text, True/False
Always goes into a Module

(not a UserForm module)

 Private Function – Only used in the module it’s in
 Public Function – Used in any module or in Excel

Can be executed in two ways:
 Called from within a Sub Procedure in VBA, OR
 Used from an Excel worksheet:
 Click on a cell, type =, then the name of your function
FUNCTION DOS AND DON’TS
Functions only do calculations
Functions DO NOT output to cells or userforms
 Do not put commands to write to cells in your function
 Do not put commands to write to userform controls in your
function

A Sub procedure performs a series of actions
 Call your function from a Sub and write the result to cells
or userforms from your Sub
ARGUMENT . AN EXAMPLE USING THE SUM FUNCTION.

This is called the ARGUMENT.
 Apply an operation to the argument and output the result
 For SUM(), it specifies what this function should sum
 In this case, we are specifying an array/range

User defined functions can have arguments too
ARGUMENT . WHEN IS IT NEEDED?
 The function operates on an argument to return a
value.

1 or more numbers

1 or more arrays/ranges

1 number

 Some functions can return a value without
operating on a variable.
NO argument needed
EXAMPLE 1. MULTIPLY 2 NUMBERS
Remember
Functions go in Modules!
EXAMPLE 1. MULTIPLY 2 NUMBERS
Requires 2 variables as the argument
(because I want it to multiply 2 numbers together)
I’ve named them x & y
EXAMPLE 1. MULTIPLY 2 NUMBERS

MUST assign each argument a data type
EXAMPLE 1. MULTIPLY 2 NUMBERS
The Function itself MUST be assigned a value
WITHIN the Function
If you don’t, it will NOT return a value
USE YOUR FUNCTION IN EXCEL
Use your function like a built-in Excel function
• Type = then the name of the
User-Defined function.
• Select the function from the
list.

• Select/Enter the arguments.
• Separate the arguments
with a comma.
EXERCISE 2. CREATE AN ADD FUNCTION
Open Lecture 9 Student Example.xlsm
Open Module1
Insert a function called Add2numbers
 Give this function 2 arguments, x and y
 Write code so that this function adds the value of x and y

Test your code in an Excel worksheet – does it
work?
CALLING FUNCTIONS FROM A SUB
CALLING FUNCTIONS FROM A SUB
CALLING FUNCTIONS FROM A SUB

The name of the
Function
CALLING FUNCTIONS FROM A SUB

This function
needs 2
arguments.
CALLING FUNCTIONS FROM A SUB
CALLING FUNCTIONS FROM A SUB

The name of the
Function
CALLING FUNCTIONS FROM A SUB

This function
needs 2
arguments.
EXERCISE 3. CALLING FUNCTIONS

Type this code and run the
UserForm.
Does it work (numbers only)?
FUNCTIONS USING ARRAYS
EXAMPLE 2. AVERAGE OF AN ARRAY

The name of
the Function
EXAMPLE 2. AVERAGE OF AN ARRAY

The argument
is an array

Any array we send to
this function will be
called array1 within
the function
EXAMPLE 2. AVERAGE OF AN ARRAY

The number of rows
in array1() is not
known in the function

Ubound(array1) returns the
number of rows in array1
EXAMPLE 2. AVERAGE OF AN ARRAY

The Function is
given a value
within the
Function
EXAMPLE 2. AVERAGE OF AN ARRAY
We can’t use it like a built-in function because the
argument is an array.

Call it from a Sub procedure
CALL A FUNCTION FROM A PROCEDURE
CALL A FUNCTION FROM A PROCEDURE
CALL A FUNCTION FROM A PROCEDURE
CALL A FUNCTION FROM A PROCEDURE
FUNCTION

V

SUB

PROCEDURE

Function procedures
 Used to return a value

Sub procedures
 Use to run a series of commands
 Does NOT return a value

For example,
 If you want to output the result of a calculation in a cell
 Do the calculation in a function
 In a Sub Procedure, output that function to a cel l

Let the cells =
the value of the
function within
the Sub
EXERCISE 4. FUNCTIONS USING ARRAYS
Open Module2
Insert a function called AverageArray2D
Inside this function write code to find the average
of a 2D array.
 You can start with the code for the 1D array and just
modify it.
 The code to calculate the number of columns in an array is
UBound(arrayName, 2)
 Recall the code to calculate the number of rows in a array is
Ubound(arrayName)

 To check that your code works,
 modify Sub MainSub() so that you read in a 2D array from Excel
(use the first 2 or 3 columns – it’s up to you)
 Output AverageArray2D from a MsgBox in Sub MainSub()
FUNCTIONS USING
RANGE OBJECTS
EXAMPLE 3. SUM A RANGE OBJECT
Insert a function called SumOfRange
In this function add together all elements of the
range:
Range object
Count the number of rows
and cols for the loops

Use a nested loop
because you have rows
and columns of data

Use .Cells() just like
with a named range

Test this function in an Excel Worksheet
EXERCISE 5. FUNCTIONS USING RANGES
Open Module2
Insert a function called AverageOfRange
 Write code to calculate the average
 All you really need to do is modify one of your previous functions

Test your function in Excel – make sure it works
CALLING PROCEDURES
CALLING A SUB FROM WITHIN ANOTHER SUB
Very similar to calling a Function
Just write Call followed by the name of the Sub

For Example
If I had a Sub Procedure called EnableControls()
and wanted to call it from within a different Sub,
I’d write:
Call EnableControls

If the sub has arguments, then write them in
brackets, just like for a function
USING SUB PROCEDURES
Use Sub procedures for
 Tasks you want to repeat in your code

For Example
Enable textboxes
Call this sub from within another procedure
USING SUB PROCEDURES
Use Sub procedures for
 Tasks you want to repeat in your code
 Breaking a large chunk of code into smaller bits

For Example
USING SUB PROCEDURES
Use Sub procedures for
 Tasks you want to repeat in your code
 Breaking a large chunk of code into smaller bits

Using Subs in this way is ‘good practice’, but not
obligatory.
LEARNING OUTCOMES
You are ready to move on when…
 LO35: You can declare and assign a range to a range object.
You also understand when and why a range object would
be used in place of a named range or array.
 LO36: You can describe what the RefEdit tool is used for. In
addition, you can assign the value of the RefEdit tool to a
range object.
 LO37: You can describe the difference between a Sub
procedure and Function procedure. Further, you can
define what arguments are in relation to functions.
 LO38: You can write and read functions with and without
arguments (to a reasonable standard). In addition, for
functions with arguments you understand the difference
between using an array, variable or range object and can
apply that knowledge in practice.
THE END

More Related Content

What's hot

Functions in python slide share
Functions in python slide shareFunctions in python slide share
Functions in python slide share
Devashish Kumar
 
Introduction to Python
Introduction to Python  Introduction to Python
Introduction to Python
Mohammed Sikander
 
Functional programming 101
Functional programming 101Functional programming 101
Functional programming 101
Maneesh Chaturvedi
 
VISUAL BASIC 6 - CONTROLS AND DECLARATIONS
VISUAL BASIC 6 - CONTROLS AND DECLARATIONSVISUAL BASIC 6 - CONTROLS AND DECLARATIONS
VISUAL BASIC 6 - CONTROLS AND DECLARATIONS
Suraj Kumar
 
predefined and user defined functions
predefined and user defined functionspredefined and user defined functions
predefined and user defined functions
Swapnil Yadav
 
Advanced Javascript
Advanced JavascriptAdvanced Javascript
Advanced Javascript
relay12
 
Functions
FunctionsFunctions
Functions
Online
 
Savitch Ch 04
Savitch Ch 04Savitch Ch 04
Savitch Ch 04
Terry Yoast
 
SAS Macro
SAS MacroSAS Macro
SAS Macro
Sonal Shrivastav
 
Python functions
Python functionsPython functions
Python functions
Prof. Dr. K. Adisesha
 
Effective Java - Design Method Signature Overload Varargs
Effective Java - Design Method Signature Overload VarargsEffective Java - Design Method Signature Overload Varargs
Effective Java - Design Method Signature Overload Varargs
Roshan Deniyage
 
Function in c++
Function in c++Function in c++
Function in c++
Kumar
 
User defined Functions in MATLAB Part 1
User defined Functions in MATLAB Part 1User defined Functions in MATLAB Part 1
User defined Functions in MATLAB Part 1
Shameer Ahmed Koya
 
Introduction to Matlab Scripts
Introduction to Matlab ScriptsIntroduction to Matlab Scripts
Introduction to Matlab Scripts
Shameer Ahmed Koya
 
Intro to tsql unit 11
Intro to tsql   unit 11Intro to tsql   unit 11
Intro to tsql unit 11
Syed Asrarali
 
Inline function
Inline functionInline function
Inline function
Tech_MX
 
Lecture 4
Lecture 4Lecture 4
Lecture 4
Mohammed Saleh
 
Applicative Functor - Part 2
Applicative Functor - Part 2Applicative Functor - Part 2
Applicative Functor - Part 2
Philip Schwarz
 
Cp module 2
Cp module 2Cp module 2
Cp module 2
Amarjith C K
 
Function C++
Function C++ Function C++
Function C++
Shahzad Afridi
 

What's hot (20)

Functions in python slide share
Functions in python slide shareFunctions in python slide share
Functions in python slide share
 
Introduction to Python
Introduction to Python  Introduction to Python
Introduction to Python
 
Functional programming 101
Functional programming 101Functional programming 101
Functional programming 101
 
VISUAL BASIC 6 - CONTROLS AND DECLARATIONS
VISUAL BASIC 6 - CONTROLS AND DECLARATIONSVISUAL BASIC 6 - CONTROLS AND DECLARATIONS
VISUAL BASIC 6 - CONTROLS AND DECLARATIONS
 
predefined and user defined functions
predefined and user defined functionspredefined and user defined functions
predefined and user defined functions
 
Advanced Javascript
Advanced JavascriptAdvanced Javascript
Advanced Javascript
 
Functions
FunctionsFunctions
Functions
 
Savitch Ch 04
Savitch Ch 04Savitch Ch 04
Savitch Ch 04
 
SAS Macro
SAS MacroSAS Macro
SAS Macro
 
Python functions
Python functionsPython functions
Python functions
 
Effective Java - Design Method Signature Overload Varargs
Effective Java - Design Method Signature Overload VarargsEffective Java - Design Method Signature Overload Varargs
Effective Java - Design Method Signature Overload Varargs
 
Function in c++
Function in c++Function in c++
Function in c++
 
User defined Functions in MATLAB Part 1
User defined Functions in MATLAB Part 1User defined Functions in MATLAB Part 1
User defined Functions in MATLAB Part 1
 
Introduction to Matlab Scripts
Introduction to Matlab ScriptsIntroduction to Matlab Scripts
Introduction to Matlab Scripts
 
Intro to tsql unit 11
Intro to tsql   unit 11Intro to tsql   unit 11
Intro to tsql unit 11
 
Inline function
Inline functionInline function
Inline function
 
Lecture 4
Lecture 4Lecture 4
Lecture 4
 
Applicative Functor - Part 2
Applicative Functor - Part 2Applicative Functor - Part 2
Applicative Functor - Part 2
 
Cp module 2
Cp module 2Cp module 2
Cp module 2
 
Function C++
Function C++ Function C++
Function C++
 

Viewers also liked

Using Functions in Excel
Using Functions in ExcelUsing Functions in Excel
Using Functions in Excel
Casey Robertson
 
Excel functions
Excel functionsExcel functions
Excel functions
cherrybear2014
 
How to find the range of a composite function
How to find the range of a composite functionHow to find the range of a composite function
How to find the range of a composite function
Wee Wen Shih
 
MS excel functions
MS excel functionsMS excel functions
MS excel functions
Marsha Superio
 
Using The Function In Excel 3
Using The Function In Excel 3Using The Function In Excel 3
Using The Function In Excel 3
norzaini
 
MS EXCEL PPT PRESENTATION
MS EXCEL PPT PRESENTATIONMS EXCEL PPT PRESENTATION
MS EXCEL PPT PRESENTATION
Mridul Bansal
 
Composition and inverse of functions
Composition  and inverse of functionsComposition  and inverse of functions
Composition and inverse of functions
Charliez Jane Soriano
 
Composite functions
Composite functionsComposite functions
Composite functions
Jessica Garcia
 
Inverse composite functions
Inverse composite functionsInverse composite functions
Inverse composite functions
Debra Wallace
 
Composition Of Functions
Composition Of FunctionsComposition Of Functions
Composition Of Functions
sjwong
 

Viewers also liked (10)

Using Functions in Excel
Using Functions in ExcelUsing Functions in Excel
Using Functions in Excel
 
Excel functions
Excel functionsExcel functions
Excel functions
 
How to find the range of a composite function
How to find the range of a composite functionHow to find the range of a composite function
How to find the range of a composite function
 
MS excel functions
MS excel functionsMS excel functions
MS excel functions
 
Using The Function In Excel 3
Using The Function In Excel 3Using The Function In Excel 3
Using The Function In Excel 3
 
MS EXCEL PPT PRESENTATION
MS EXCEL PPT PRESENTATIONMS EXCEL PPT PRESENTATION
MS EXCEL PPT PRESENTATION
 
Composition and inverse of functions
Composition  and inverse of functionsComposition  and inverse of functions
Composition and inverse of functions
 
Composite functions
Composite functionsComposite functions
Composite functions
 
Inverse composite functions
Inverse composite functionsInverse composite functions
Inverse composite functions
 
Composition Of Functions
Composition Of FunctionsComposition Of Functions
Composition Of Functions
 

Similar to MA3696 Lecture 9

Python programming variables and comment
Python programming variables and commentPython programming variables and comment
Python programming variables and comment
MalligaarjunanN
 
Functions in C++
Functions in C++Functions in C++
Functions in C++
home
 
functions.pptx
functions.pptxfunctions.pptx
functions.pptx
KavithaChekuri3
 
Chapter9 more on database and sql
Chapter9 more on database and sqlChapter9 more on database and sql
Chapter9 more on database and sql
KV(AFS) Utarlai, Barmer (Rajasthan)
 
C language 3
C language 3C language 3
C language 3
Arafat Bin Reza
 
C Programming - Refresher - Part II
C Programming - Refresher - Part II C Programming - Refresher - Part II
C Programming - Refresher - Part II
Emertxe Information Technologies Pvt Ltd
 
C functions
C functionsC functions
Functional Objects & Function and Closures
Functional Objects  & Function and ClosuresFunctional Objects  & Function and Closures
Functional Objects & Function and Closures
Sandip Kumar
 
Javascript functions
Javascript functionsJavascript functions
Javascript functions
Alaref Abushaala
 
Module 3-Functions
Module 3-FunctionsModule 3-Functions
Module 3-Functions
nikshaikh786
 
Python programming - Functions and list and tuples
Python programming - Functions and list and tuplesPython programming - Functions and list and tuples
Python programming - Functions and list and tuples
MalligaarjunanN
 
Python Functions.pptx
Python Functions.pptxPython Functions.pptx
Python Functions.pptx
AnuragBharti27
 
Python Functions.pptx
Python Functions.pptxPython Functions.pptx
Python Functions.pptx
AnuragBharti27
 
Functional Objects & Function and Closures
Functional Objects  & Function and ClosuresFunctional Objects  & Function and Closures
Functional Objects & Function and Closures
Sandip Kumar
 
Scala oo (1)
Scala oo (1)Scala oo (1)
Scala oo (1)
Sandip Kumar
 
Functions in C++
Functions in C++Functions in C++
Functions in C++
home
 
functions modules and exceptions handlings.ppt
functions modules and exceptions handlings.pptfunctions modules and exceptions handlings.ppt
functions modules and exceptions handlings.ppt
Rajasekhar364622
 
Ma3696 Lecture 1
Ma3696 Lecture 1Ma3696 Lecture 1
Ma3696 Lecture 1
Brunel University
 
04. WORKING WITH FUNCTIONS-2 (1).pptx
04. WORKING WITH FUNCTIONS-2 (1).pptx04. WORKING WITH FUNCTIONS-2 (1).pptx
04. WORKING WITH FUNCTIONS-2 (1).pptx
Manas40552
 
Functions in c language
Functions in c languageFunctions in c language
Functions in c language
Tanmay Modi
 

Similar to MA3696 Lecture 9 (20)

Python programming variables and comment
Python programming variables and commentPython programming variables and comment
Python programming variables and comment
 
Functions in C++
Functions in C++Functions in C++
Functions in C++
 
functions.pptx
functions.pptxfunctions.pptx
functions.pptx
 
Chapter9 more on database and sql
Chapter9 more on database and sqlChapter9 more on database and sql
Chapter9 more on database and sql
 
C language 3
C language 3C language 3
C language 3
 
C Programming - Refresher - Part II
C Programming - Refresher - Part II C Programming - Refresher - Part II
C Programming - Refresher - Part II
 
C functions
C functionsC functions
C functions
 
Functional Objects & Function and Closures
Functional Objects  & Function and ClosuresFunctional Objects  & Function and Closures
Functional Objects & Function and Closures
 
Javascript functions
Javascript functionsJavascript functions
Javascript functions
 
Module 3-Functions
Module 3-FunctionsModule 3-Functions
Module 3-Functions
 
Python programming - Functions and list and tuples
Python programming - Functions and list and tuplesPython programming - Functions and list and tuples
Python programming - Functions and list and tuples
 
Python Functions.pptx
Python Functions.pptxPython Functions.pptx
Python Functions.pptx
 
Python Functions.pptx
Python Functions.pptxPython Functions.pptx
Python Functions.pptx
 
Functional Objects & Function and Closures
Functional Objects  & Function and ClosuresFunctional Objects  & Function and Closures
Functional Objects & Function and Closures
 
Scala oo (1)
Scala oo (1)Scala oo (1)
Scala oo (1)
 
Functions in C++
Functions in C++Functions in C++
Functions in C++
 
functions modules and exceptions handlings.ppt
functions modules and exceptions handlings.pptfunctions modules and exceptions handlings.ppt
functions modules and exceptions handlings.ppt
 
Ma3696 Lecture 1
Ma3696 Lecture 1Ma3696 Lecture 1
Ma3696 Lecture 1
 
04. WORKING WITH FUNCTIONS-2 (1).pptx
04. WORKING WITH FUNCTIONS-2 (1).pptx04. WORKING WITH FUNCTIONS-2 (1).pptx
04. WORKING WITH FUNCTIONS-2 (1).pptx
 
Functions in c language
Functions in c languageFunctions in c language
Functions in c language
 

More from Brunel University

MA3696 Lecture 8
MA3696 Lecture 8MA3696 Lecture 8
MA3696 Lecture 8
Brunel University
 
MA3696 Lecture 7
MA3696 Lecture 7MA3696 Lecture 7
MA3696 Lecture 7
Brunel University
 
MA3696 Lecture 6
MA3696 Lecture 6MA3696 Lecture 6
MA3696 Lecture 6
Brunel University
 
MA3696 Lecture 5
MA3696 Lecture 5MA3696 Lecture 5
MA3696 Lecture 5
Brunel University
 
Ma3696 lecture 4
Ma3696 lecture 4Ma3696 lecture 4
Ma3696 lecture 4
Brunel University
 
Ma3696 Lecture 3
Ma3696 Lecture 3Ma3696 Lecture 3
Ma3696 Lecture 3
Brunel University
 
Ma3696 Lecture 2
Ma3696 Lecture 2Ma3696 Lecture 2
Ma3696 Lecture 2
Brunel University
 
Ma3696 Lecture 0
Ma3696 Lecture 0Ma3696 Lecture 0
Ma3696 Lecture 0
Brunel University
 

More from Brunel University (8)

MA3696 Lecture 8
MA3696 Lecture 8MA3696 Lecture 8
MA3696 Lecture 8
 
MA3696 Lecture 7
MA3696 Lecture 7MA3696 Lecture 7
MA3696 Lecture 7
 
MA3696 Lecture 6
MA3696 Lecture 6MA3696 Lecture 6
MA3696 Lecture 6
 
MA3696 Lecture 5
MA3696 Lecture 5MA3696 Lecture 5
MA3696 Lecture 5
 
Ma3696 lecture 4
Ma3696 lecture 4Ma3696 lecture 4
Ma3696 lecture 4
 
Ma3696 Lecture 3
Ma3696 Lecture 3Ma3696 Lecture 3
Ma3696 Lecture 3
 
Ma3696 Lecture 2
Ma3696 Lecture 2Ma3696 Lecture 2
Ma3696 Lecture 2
 
Ma3696 Lecture 0
Ma3696 Lecture 0Ma3696 Lecture 0
Ma3696 Lecture 0
 

Recently uploaded

How to Fix the Import Error in the Odoo 17
How to Fix the Import Error in the Odoo 17How to Fix the Import Error in the Odoo 17
How to Fix the Import Error in the Odoo 17
Celine George
 
The basics of sentences session 6pptx.pptx
The basics of sentences session 6pptx.pptxThe basics of sentences session 6pptx.pptx
The basics of sentences session 6pptx.pptx
heathfieldcps1
 
Film vocab for eal 3 students: Australia the movie
Film vocab for eal 3 students: Australia the movieFilm vocab for eal 3 students: Australia the movie
Film vocab for eal 3 students: Australia the movie
Nicholas Montgomery
 
South African Journal of Science: Writing with integrity workshop (2024)
South African Journal of Science: Writing with integrity workshop (2024)South African Journal of Science: Writing with integrity workshop (2024)
South African Journal of Science: Writing with integrity workshop (2024)
Academy of Science of South Africa
 
Introduction to AI for Nonprofits with Tapp Network
Introduction to AI for Nonprofits with Tapp NetworkIntroduction to AI for Nonprofits with Tapp Network
Introduction to AI for Nonprofits with Tapp Network
TechSoup
 
ANATOMY AND BIOMECHANICS OF HIP JOINT.pdf
ANATOMY AND BIOMECHANICS OF HIP JOINT.pdfANATOMY AND BIOMECHANICS OF HIP JOINT.pdf
ANATOMY AND BIOMECHANICS OF HIP JOINT.pdf
Priyankaranawat4
 
BÀI TẬP BỔ TRỢ TIẾNG ANH 8 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2023-2024 (CÓ FI...
BÀI TẬP BỔ TRỢ TIẾNG ANH 8 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2023-2024 (CÓ FI...BÀI TẬP BỔ TRỢ TIẾNG ANH 8 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2023-2024 (CÓ FI...
BÀI TẬP BỔ TRỢ TIẾNG ANH 8 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2023-2024 (CÓ FI...
Nguyen Thanh Tu Collection
 
RPMS TEMPLATE FOR SCHOOL YEAR 2023-2024 FOR TEACHER 1 TO TEACHER 3
RPMS TEMPLATE FOR SCHOOL YEAR 2023-2024 FOR TEACHER 1 TO TEACHER 3RPMS TEMPLATE FOR SCHOOL YEAR 2023-2024 FOR TEACHER 1 TO TEACHER 3
RPMS TEMPLATE FOR SCHOOL YEAR 2023-2024 FOR TEACHER 1 TO TEACHER 3
IreneSebastianRueco1
 
Liberal Approach to the Study of Indian Politics.pdf
Liberal Approach to the Study of Indian Politics.pdfLiberal Approach to the Study of Indian Politics.pdf
Liberal Approach to the Study of Indian Politics.pdf
WaniBasim
 
C1 Rubenstein AP HuG xxxxxxxxxxxxxx.pptx
C1 Rubenstein AP HuG xxxxxxxxxxxxxx.pptxC1 Rubenstein AP HuG xxxxxxxxxxxxxx.pptx
C1 Rubenstein AP HuG xxxxxxxxxxxxxx.pptx
mulvey2
 
Azure Interview Questions and Answers PDF By ScholarHat
Azure Interview Questions and Answers PDF By ScholarHatAzure Interview Questions and Answers PDF By ScholarHat
Azure Interview Questions and Answers PDF By ScholarHat
Scholarhat
 
Types of Herbal Cosmetics its standardization.
Types of Herbal Cosmetics its standardization.Types of Herbal Cosmetics its standardization.
Types of Herbal Cosmetics its standardization.
Ashokrao Mane college of Pharmacy Peth-Vadgaon
 
Top five deadliest dog breeds in America
Top five deadliest dog breeds in AmericaTop five deadliest dog breeds in America
Top five deadliest dog breeds in America
Bisnar Chase Personal Injury Attorneys
 
World environment day ppt For 5 June 2024
World environment day ppt For 5 June 2024World environment day ppt For 5 June 2024
World environment day ppt For 5 June 2024
ak6969907
 
DRUGS AND ITS classification slide share
DRUGS AND ITS classification slide shareDRUGS AND ITS classification slide share
DRUGS AND ITS classification slide share
taiba qazi
 
বাংলাদেশ অর্থনৈতিক সমীক্ষা (Economic Review) ২০২৪ UJS App.pdf
বাংলাদেশ অর্থনৈতিক সমীক্ষা (Economic Review) ২০২৪ UJS App.pdfবাংলাদেশ অর্থনৈতিক সমীক্ষা (Economic Review) ২০২৪ UJS App.pdf
বাংলাদেশ অর্থনৈতিক সমীক্ষা (Economic Review) ২০২৪ UJS App.pdf
eBook.com.bd (প্রয়োজনীয় বাংলা বই)
 
Smart-Money for SMC traders good time and ICT
Smart-Money for SMC traders good time and ICTSmart-Money for SMC traders good time and ICT
Smart-Money for SMC traders good time and ICT
simonomuemu
 
writing about opinions about Australia the movie
writing about opinions about Australia the moviewriting about opinions about Australia the movie
writing about opinions about Australia the movie
Nicholas Montgomery
 
S1-Introduction-Biopesticides in ICM.pptx
S1-Introduction-Biopesticides in ICM.pptxS1-Introduction-Biopesticides in ICM.pptx
S1-Introduction-Biopesticides in ICM.pptx
tarandeep35
 
Digital Artefact 1 - Tiny Home Environmental Design
Digital Artefact 1 - Tiny Home Environmental DesignDigital Artefact 1 - Tiny Home Environmental Design
Digital Artefact 1 - Tiny Home Environmental Design
amberjdewit93
 

Recently uploaded (20)

How to Fix the Import Error in the Odoo 17
How to Fix the Import Error in the Odoo 17How to Fix the Import Error in the Odoo 17
How to Fix the Import Error in the Odoo 17
 
The basics of sentences session 6pptx.pptx
The basics of sentences session 6pptx.pptxThe basics of sentences session 6pptx.pptx
The basics of sentences session 6pptx.pptx
 
Film vocab for eal 3 students: Australia the movie
Film vocab for eal 3 students: Australia the movieFilm vocab for eal 3 students: Australia the movie
Film vocab for eal 3 students: Australia the movie
 
South African Journal of Science: Writing with integrity workshop (2024)
South African Journal of Science: Writing with integrity workshop (2024)South African Journal of Science: Writing with integrity workshop (2024)
South African Journal of Science: Writing with integrity workshop (2024)
 
Introduction to AI for Nonprofits with Tapp Network
Introduction to AI for Nonprofits with Tapp NetworkIntroduction to AI for Nonprofits with Tapp Network
Introduction to AI for Nonprofits with Tapp Network
 
ANATOMY AND BIOMECHANICS OF HIP JOINT.pdf
ANATOMY AND BIOMECHANICS OF HIP JOINT.pdfANATOMY AND BIOMECHANICS OF HIP JOINT.pdf
ANATOMY AND BIOMECHANICS OF HIP JOINT.pdf
 
BÀI TẬP BỔ TRỢ TIẾNG ANH 8 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2023-2024 (CÓ FI...
BÀI TẬP BỔ TRỢ TIẾNG ANH 8 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2023-2024 (CÓ FI...BÀI TẬP BỔ TRỢ TIẾNG ANH 8 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2023-2024 (CÓ FI...
BÀI TẬP BỔ TRỢ TIẾNG ANH 8 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2023-2024 (CÓ FI...
 
RPMS TEMPLATE FOR SCHOOL YEAR 2023-2024 FOR TEACHER 1 TO TEACHER 3
RPMS TEMPLATE FOR SCHOOL YEAR 2023-2024 FOR TEACHER 1 TO TEACHER 3RPMS TEMPLATE FOR SCHOOL YEAR 2023-2024 FOR TEACHER 1 TO TEACHER 3
RPMS TEMPLATE FOR SCHOOL YEAR 2023-2024 FOR TEACHER 1 TO TEACHER 3
 
Liberal Approach to the Study of Indian Politics.pdf
Liberal Approach to the Study of Indian Politics.pdfLiberal Approach to the Study of Indian Politics.pdf
Liberal Approach to the Study of Indian Politics.pdf
 
C1 Rubenstein AP HuG xxxxxxxxxxxxxx.pptx
C1 Rubenstein AP HuG xxxxxxxxxxxxxx.pptxC1 Rubenstein AP HuG xxxxxxxxxxxxxx.pptx
C1 Rubenstein AP HuG xxxxxxxxxxxxxx.pptx
 
Azure Interview Questions and Answers PDF By ScholarHat
Azure Interview Questions and Answers PDF By ScholarHatAzure Interview Questions and Answers PDF By ScholarHat
Azure Interview Questions and Answers PDF By ScholarHat
 
Types of Herbal Cosmetics its standardization.
Types of Herbal Cosmetics its standardization.Types of Herbal Cosmetics its standardization.
Types of Herbal Cosmetics its standardization.
 
Top five deadliest dog breeds in America
Top five deadliest dog breeds in AmericaTop five deadliest dog breeds in America
Top five deadliest dog breeds in America
 
World environment day ppt For 5 June 2024
World environment day ppt For 5 June 2024World environment day ppt For 5 June 2024
World environment day ppt For 5 June 2024
 
DRUGS AND ITS classification slide share
DRUGS AND ITS classification slide shareDRUGS AND ITS classification slide share
DRUGS AND ITS classification slide share
 
বাংলাদেশ অর্থনৈতিক সমীক্ষা (Economic Review) ২০২৪ UJS App.pdf
বাংলাদেশ অর্থনৈতিক সমীক্ষা (Economic Review) ২০২৪ UJS App.pdfবাংলাদেশ অর্থনৈতিক সমীক্ষা (Economic Review) ২০২৪ UJS App.pdf
বাংলাদেশ অর্থনৈতিক সমীক্ষা (Economic Review) ২০২৪ UJS App.pdf
 
Smart-Money for SMC traders good time and ICT
Smart-Money for SMC traders good time and ICTSmart-Money for SMC traders good time and ICT
Smart-Money for SMC traders good time and ICT
 
writing about opinions about Australia the movie
writing about opinions about Australia the moviewriting about opinions about Australia the movie
writing about opinions about Australia the movie
 
S1-Introduction-Biopesticides in ICM.pptx
S1-Introduction-Biopesticides in ICM.pptxS1-Introduction-Biopesticides in ICM.pptx
S1-Introduction-Biopesticides in ICM.pptx
 
Digital Artefact 1 - Tiny Home Environmental Design
Digital Artefact 1 - Tiny Home Environmental DesignDigital Artefact 1 - Tiny Home Environmental Design
Digital Artefact 1 - Tiny Home Environmental Design
 

MA3696 Lecture 9

  • 2. SUMMARY Range objects Obtaining a range using the RefEdit control User-Defined Functions  Without arguments  With arguments  Variables, constants, arrays and range objects
  • 3. RANGE OBJECTS A cross between a named range and an array
  • 4. RANGE OBJECTS Range objects are an alternative to using arrays and named ranges. Range objects are preferred when:  You are using the RefEdit control to allow users to select data for a program.  You are creating user defined functions which you want to use within Excel worksheets (as opposed to using them solely within your code).  You are creating an Excel add-in and don’t want to clog up the user’s workbook with range names.
  • 5. DECLARING A RANGE OBJECT A Range is a data type. So we declare a range object as: Dim rangeObj as Range  Where rangeObj is the name you want to assign to the range object Assign a range object a range within a procedure: Set rangeObj = Range Set rangeObj = Range(“RangeName”)  Where Range is a range in Excel and RangeName is a named range in Excel.  For example, Set stockRange = Range(Cells(1,1), Cells(1,25)) Set stockRange = Range(“StockPrices”)
  • 6. METHODS APPLIED TO RANGE OJBECTS You can do nearly everything the same as a range or named range in Excel. For example:  Count rows or columns rangeObj.Rows.Count rangeObj.Columns.Count  Refer to cells within the range rangeObj.Cells(i, j).Value
  • 7. REFEDIT CONTROL Letting the user select the range of data
  • 8. REFEDIT RefEdit is a UserForm control: Allows user to select a range in Excel Set this selection as a range object in your code Set rangeObj = Range(RefEdit.Value)  Where RefEdit is the (Name) of the control Then use the range however you need to  In a built-in function  In a user defined function  In place of a named range
  • 9. EXERCISE 1. REFEDIT Open Lecture 9 Student Example.xlsm Open UserForm2 In the sub for the command button code the following:  Declare a range object called userSelect  Set this range object equal to the value of the RefEdit control  Test that the works by outputting the range object to some cells  Use the .Columns.Count and .Rows.Count property to assist you  Start the output in Cells(1,6) of Sheet 1  Remember, to ‘copy’ or ‘output’ you just need to set the two ranges equal to each other  (make sure to put .Value at the end of each range)
  • 11. WHAT IS A USER DEFINED FUNCTION? Designed/created by YOU, the USER  Similar to an Excel built-in function Returns a value: number, text, True/False Always goes into a Module (not a UserForm module)  Private Function – Only used in the module it’s in  Public Function – Used in any module or in Excel Can be executed in two ways:  Called from within a Sub Procedure in VBA, OR  Used from an Excel worksheet:  Click on a cell, type =, then the name of your function
  • 12. FUNCTION DOS AND DON’TS Functions only do calculations Functions DO NOT output to cells or userforms  Do not put commands to write to cells in your function  Do not put commands to write to userform controls in your function A Sub procedure performs a series of actions  Call your function from a Sub and write the result to cells or userforms from your Sub
  • 13. ARGUMENT . AN EXAMPLE USING THE SUM FUNCTION. This is called the ARGUMENT.  Apply an operation to the argument and output the result  For SUM(), it specifies what this function should sum  In this case, we are specifying an array/range User defined functions can have arguments too
  • 14. ARGUMENT . WHEN IS IT NEEDED?  The function operates on an argument to return a value. 1 or more numbers 1 or more arrays/ranges 1 number  Some functions can return a value without operating on a variable. NO argument needed
  • 15. EXAMPLE 1. MULTIPLY 2 NUMBERS Remember Functions go in Modules!
  • 16. EXAMPLE 1. MULTIPLY 2 NUMBERS Requires 2 variables as the argument (because I want it to multiply 2 numbers together) I’ve named them x & y
  • 17. EXAMPLE 1. MULTIPLY 2 NUMBERS MUST assign each argument a data type
  • 18. EXAMPLE 1. MULTIPLY 2 NUMBERS The Function itself MUST be assigned a value WITHIN the Function If you don’t, it will NOT return a value
  • 19. USE YOUR FUNCTION IN EXCEL Use your function like a built-in Excel function • Type = then the name of the User-Defined function. • Select the function from the list. • Select/Enter the arguments. • Separate the arguments with a comma.
  • 20. EXERCISE 2. CREATE AN ADD FUNCTION Open Lecture 9 Student Example.xlsm Open Module1 Insert a function called Add2numbers  Give this function 2 arguments, x and y  Write code so that this function adds the value of x and y Test your code in an Excel worksheet – does it work?
  • 23. CALLING FUNCTIONS FROM A SUB The name of the Function
  • 24. CALLING FUNCTIONS FROM A SUB This function needs 2 arguments.
  • 26. CALLING FUNCTIONS FROM A SUB The name of the Function
  • 27. CALLING FUNCTIONS FROM A SUB This function needs 2 arguments.
  • 28. EXERCISE 3. CALLING FUNCTIONS Type this code and run the UserForm. Does it work (numbers only)?
  • 30. EXAMPLE 2. AVERAGE OF AN ARRAY The name of the Function
  • 31. EXAMPLE 2. AVERAGE OF AN ARRAY The argument is an array Any array we send to this function will be called array1 within the function
  • 32. EXAMPLE 2. AVERAGE OF AN ARRAY The number of rows in array1() is not known in the function Ubound(array1) returns the number of rows in array1
  • 33. EXAMPLE 2. AVERAGE OF AN ARRAY The Function is given a value within the Function
  • 34. EXAMPLE 2. AVERAGE OF AN ARRAY We can’t use it like a built-in function because the argument is an array. Call it from a Sub procedure
  • 35. CALL A FUNCTION FROM A PROCEDURE
  • 36. CALL A FUNCTION FROM A PROCEDURE
  • 37. CALL A FUNCTION FROM A PROCEDURE
  • 38. CALL A FUNCTION FROM A PROCEDURE
  • 39. FUNCTION V SUB PROCEDURE Function procedures  Used to return a value Sub procedures  Use to run a series of commands  Does NOT return a value For example,  If you want to output the result of a calculation in a cell  Do the calculation in a function  In a Sub Procedure, output that function to a cel l Let the cells = the value of the function within the Sub
  • 40. EXERCISE 4. FUNCTIONS USING ARRAYS Open Module2 Insert a function called AverageArray2D Inside this function write code to find the average of a 2D array.  You can start with the code for the 1D array and just modify it.  The code to calculate the number of columns in an array is UBound(arrayName, 2)  Recall the code to calculate the number of rows in a array is Ubound(arrayName)  To check that your code works,  modify Sub MainSub() so that you read in a 2D array from Excel (use the first 2 or 3 columns – it’s up to you)  Output AverageArray2D from a MsgBox in Sub MainSub()
  • 42. EXAMPLE 3. SUM A RANGE OBJECT Insert a function called SumOfRange In this function add together all elements of the range: Range object Count the number of rows and cols for the loops Use a nested loop because you have rows and columns of data Use .Cells() just like with a named range Test this function in an Excel Worksheet
  • 43. EXERCISE 5. FUNCTIONS USING RANGES Open Module2 Insert a function called AverageOfRange  Write code to calculate the average  All you really need to do is modify one of your previous functions Test your function in Excel – make sure it works
  • 45. CALLING A SUB FROM WITHIN ANOTHER SUB Very similar to calling a Function Just write Call followed by the name of the Sub For Example If I had a Sub Procedure called EnableControls() and wanted to call it from within a different Sub, I’d write: Call EnableControls If the sub has arguments, then write them in brackets, just like for a function
  • 46. USING SUB PROCEDURES Use Sub procedures for  Tasks you want to repeat in your code For Example Enable textboxes Call this sub from within another procedure
  • 47. USING SUB PROCEDURES Use Sub procedures for  Tasks you want to repeat in your code  Breaking a large chunk of code into smaller bits For Example
  • 48. USING SUB PROCEDURES Use Sub procedures for  Tasks you want to repeat in your code  Breaking a large chunk of code into smaller bits Using Subs in this way is ‘good practice’, but not obligatory.
  • 49. LEARNING OUTCOMES You are ready to move on when…  LO35: You can declare and assign a range to a range object. You also understand when and why a range object would be used in place of a named range or array.  LO36: You can describe what the RefEdit tool is used for. In addition, you can assign the value of the RefEdit tool to a range object.  LO37: You can describe the difference between a Sub procedure and Function procedure. Further, you can define what arguments are in relation to functions.  LO38: You can write and read functions with and without arguments (to a reasonable standard). In addition, for functions with arguments you understand the difference between using an array, variable or range object and can apply that knowledge in practice.