2oraisit Excel VBA Sub Procedure and Functions
Lesson 5: Sub Procedure and Functions
seo seacies ®
eae @) C crcl vival base aC fo) a)
vba date a) C vba extn a) C ea COS a)
ub Procedure
|ASub procedure in Excel VBA is « procedure that performs a specific
sk on
rn values, but itdoos not roturn a value assoc!
-0n return value through a variable name. Subroutines are usually used to accept input rom the user, display
information, print information, manipulate propertics or perform some othor tasks Itis @ program code by itsaf andit isnt an event
cod with
procedure because itis not associated with « runtime procedure or an Excel VBA control such as @ command button tis called by the main
program whenever itis required to perform a certain task Sub procedures help to make programs smallor and casior to manage. A
Subroutine begins with a Sub statement ond ends with an Endl Sub:
y
Open New Company In UK
‘Choose @ Company Name- Register Online in Minutes. Quick and Ea
Archers
—
The program structure of @ sub procedures a follows
Sub subProg(argurents)
nd su
Sub procedure are called by the main program using the Call keyword
Sub ManProgt
cant suvrreg()
No Hidden Extras Or Surprise Costs. Basic Startup Package
£16.99.
Form Your New Company Online. UK's Most Trusted Provider Of Con
Archers
—
‘Aub procedure i ifferent from a function that it
Joos not return @ value direcly. You can include parameters in @ cub procedure.
Example 51
In this example, the main program calls the sub procedure finalHiddon and execute it.The ond results a message box that dieplay the
hidden text
Private Sub CosmandButton_Click()
call finatiaden
nd Su
Sub Finaitdden()
ica ernest
hilps:ifexcelvbatutor comb
5 lessonS.him 142oraisit Excel VBA Sub Procedure and Functions
HspBox hidden txt
nd Sub
Bromple 52
Private Sub Cannandauttond click()
all salary(1e, 3¢0)
nd suo
‘sub salary(wage AS Single, hours As Single)
MsgBox wage * hours
nd suo
xo
BBY ule lea 5 Google oS Lee
EM Soe gaia al ta IS he DEY aL Se
leamdigita.wthgoogle.com
In this example, the Call command calls the subroutine salary and passes the parametors 10 end 300 tot twill calculate the salary based on
‘wage per hour anc number af hours and display on the massage box,
5.2 Functions
In 8ol VBA o unetion isto a sub procedure bur the main purpose of tho funtion Isto aceopt an input trom the sor and return &
‘alia which a pom onto the main progr ta fri te execution Thera ate ta tps of kanctiona, the bull notions (or nba
{unctions) andthe functions eroated by the prograramrs, or simply calle usor-dtined functions
‘The fret bull-In function that we have already learned and familar with ite usage Ie the Message Box. We are not going to repeat here but we
‘shall tako a look atts syntex once mare, io.
essagestsgton(Pronpt, Style Valve, Title)
"Now we shal examine the nest commonly used function in Excel VBA the InputBox function.
5.21 InputBox function
{An Inputdox() function dlsplays « message box whore the user can entor 6 value oF @ message inthe form of tox. The syntaxis,
ytessagecinputsox(Pronpt, Title, default text, x-position, y-position)
‘myMassage isa variant data type but typically itis declared as a string, which aecepts the message input by the users. The arguments are
‘oxplainod as ‘ollows:
‘+ Prompt represonts the mossage aisplayod normally as a question asked.
+ Title represants the title ofthe Input Box.
‘+ dofcuit-toxt represents the default text that appears inthe input fold where the user can use tas the intonded input
‘+ x-position and y- position represent the position or the coordinate ofthe input box.
Example 51
In this example, we insert a label andl a command button into the MS Excel spreadsheet. Double click on the command button and enter the
Excel VBA code as follows:
Private Sub Conmandouttond.click()
Dim userwsg AS String
userisg = inputsox("what is your ressage?",
TF usertisg @ °* Then
sgBox( usertsg)
rise
MsgBox( "No Message")
nd 1
nd Sune
lessage Entry Forn", “Enter your nessge here", S08, 782)
+ The InputBoxs shown in Figure S1
hilpsifexcevbatutorconvba.lessonS.ntm 2142oraisits Excel VBA Sub Procedure and Functions
a]
[seen
=
Figure 51
521 Creating User-Defined Functions
‘The syntaxto create a User-Defined function is as follows:
Public Function funetiontame (Arg AS datatype,...) As datatype
Private Function functionane (Arg As datatype,
As datatype
Public indicates thatthe function is applicable to the whole project while Private indicates thatthe function i only applicable to a cartain
‘module or procedure.
Incotder to ereate « user-dotined function in Xcel VBA you need to go into the Visual Base Eltor In MS Excel Spreadshootin the Visual Basic
Fito, click on Insert on the menu bar to insert a module into the project Enter the following code as shown in Figure 62. Ths function sto
‘caleulate the cube root of a number.
TO Fle ESt Vw met Fert Dei fin Took dns row Hep
[Gd 228 90 + uae Nees @ usar
Gaoetoor = nan 7 &) me
High Quality Electric Chain Hoists Supplier. Call Now and Ge
‘ 1-50t Electric Chain Hoist Provided by China Leading Supplier. Get Q
sion ty f
Elsen Crane
ue am mor
"Now enter the function Cubooot just ke you enter the formula of MS Excol as shown in Figure 63. The value of cube root forthe number in
‘coll 4 will appoarin call Da.
hilpsifexcelvbatutorconvba lessonS.ntm 3/42oraisits Excel VBA Sub Procedure and Functions
@ aoe
ge
Ge SB uctantcme Fe SE rere
Baie di mo secur * i= “ 4 nun diaon e
be ~ F =cubenoatica)
Gee ee
a
Figure 63
‘We will deal with more user-defined functions in future lessons
er rl Mealy oaeae,
“Se one o
ms tf? o_ el
7 gesue ol = | i
Electric Chain Hoist for Sale Excel VBA string functions Digital Marketing Courses - Excel VBA Lesson 19: The
Range Object in Excel VBA
a
4
.
Learn to Code Online Excel VBA Mathematical Excel VBA Lesson 3:
Functions Working with Array
«Previou Next Lesson)
excel vial base 4%) ¢ arian progam a) ¢ coding and progranming ___@)
cel orulbs a) C sum excel aC ic tori a)
nya 2008 Drisew Yoon Klong Al hts reserved Last update o422010 1752272 [Baar ale)
Conse Facebok Page
hilpsifexcelvbatutorcomivba.lessonS.ntm 4/4