0% found this document useful (0 votes)
6 views

Modules - Functions in Vba

Uploaded by

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

Modules - Functions in Vba

Uploaded by

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

Modules in vba

Learning objectives

• When to use Sub procedures or Subroutines


• Functions
Modules
• Block of program code that performs a specific task
• Two types of modules in Visual Basic
• Sub : does not return a value/ perform multiple tasks
• Function: always return a value/ perform one specific task only
Advantages of using functions
• A function is a small program built with a specific purpose that, when used,
will return a value to the calling procedure or spreadsheet cell(s). Two
types:
• user-defined : created by the user using vba
• Built-in functions e.g inputbox(), sum() functions – already available in
excel
• E.g in tp 4 where a sub procedure was used to calculate both area and
circumference of circle in the same module
• This module can be rewritten using a function to calculate the area of
circle and another function to calculate circumference.
• Advantages of functions: can be used directly in excel/ or in other modules.
(see example in next slides)
Creating Your Own VBA Functions

• The basic syntax for creating a function procedure in VBA is as


follows:
Private/Public Function FunctionName(parameter list) as type
'Function procedure code is listed here
FunctionName = Return value
End Function
Example of user defined function
Public Function calculate_area(r As Single) As Single
Const pi = 22 / 7
calculate_area = pi * r * r
End Function
output
Excel inbuilt functions
• Max()
• Sum()
• Average()

• String functions
• Length()
• Mid()
• Ltrim()
• Rtrim()
Tp– using inbuilt string functions
• Refer to separate handout for tp5 called funwithstring
• using in-built vba string functions
• Reference book: Microsoft vba programming for the absolute beginner pg
42.
• Additional work:
• 1.use vba code to format the output as shown in the handout/ebook.

• 2. Refer to tp 4 create a separate function to calculate circumference of


circle for a series of radius (refer to example of function to calculate area)
• Online refererence (user defined functions)
https://www.youtube.com/watch?v=iDbe2Rsofp8&t=61s

You might also like