Professional Documents
Culture Documents
Advertisements
PreviousPage
NextPage
VBA stands for Visual Basic for Applications an event driven programming language from
Microsoft that is now predominantly used with Microsoft office applications such as MS
Excel,MSWordandMSAccess.
Ithelpstechiestobuildcustomizedapplicationsandsolutionstoenhancethecapabilitiesof
those applications. The advantage of this facility is that we NEED NOT have visual basic
installedonourPCbutinstallingofficewillimplicitlyhelpustoachievethepurpose.
WecanuseVBAinallofficeversionsrightfromMSOffice97toMSOffice2013andalso
withanyofthelatestversionsavailable.AmongVBA,ExcelVBAisthemostpopularoneand
the reason for using VBA is that we can build very powerful tools in MS Excel using linear
programming.
ApplicationofVBA
You might wonder why we need to use VBA in excel as MSExcel itself provides loads on
inbuiltfunctions.MSExcelprovidesonlybasicinbuiltfunctionswhichmaynotbesufficientto
perform complex calculations. Under those circumstances VBA becomes the most obvious
solution.
Oneofthebestexamplesisitisveryhardtocalculatemonthlyrepaymentforaloanusing
Excel'sbuiltinformulasbutitiseasytoprogramaVBAforsuchcalculation.
AccessingVBAEditor
InExcelwindow,press"ALT+F11".VBAwindowopensasshownbelow.
ExcelVBAMacros
Inthischapterletusunderstandhowtowriteasimplemacro.Letustakeitstepbystep.
Step1.Firstletusenable'Developer'menuinExcel20XX.Todothesame,clickonFile
>>Options.
Step2.ClickCustomizeRibbonTabandcheck'Developer'andclick'OK'.
Step3.The'Developer'ribbonappearsinmenubar.
Step4.click'VisualBasic'ButtontoopenVBAEditor.
Step5.NowLetusstartscriptingbyaddingabutton.Click'Insert'>>Select'button'.
Step6.PerformaRightClickandchoose'properties'.
Step7.EditthenameandCaptionasshownbelow.
Step 8. Now Double click the button, the sub procedure outline would be displayed as
shownbelow.
Step9.Letusstartcodingbysimplyaddingamessage.
PrivateSubsay_helloworld_Click()
MsgBox"Hi"
EndSub
Step 10. Now you can click the button to execute the subprocedure. The Output of the
subprocedureisshownbelow.Wewilldemostratefurtherchaptersusingasimplebuttonas
explainedfromstep#1to10.HenceItisimportanttounderstandthischapterthoroughly.
ExcelVBATerminologies
In this chapter let us understand commonly used excel VBA terminologies. These
terminologies will be used in further modules hence understanding each one of these is a
key.
Modules
1.Modulesistheareawherecodeiswritten.ThisisanewWorkbookhencetherearen'tany
Modules.
2.ToinsertaModulenavigatetoInsert>>Module.Onceamoduleisinserted'module1'is
created. Within the modules, we can write VBA code and the code is written within a
Procedure.AProcedure/SubProcedureisaseriesofVBAstatementsinstructingwhattodo.
Procedure
ProceduresaregroupofstatementsthatareexecutedasawholewhichinstructsExcelhow
toperformaspecifictask.Thetaskperformedcanbeverysimpleorverycomplicatedand
itisagoodpracticetobreakdowncomplicatedproceduresintosmallerones.
ThetwomaintypesofProceduresareSubandFunction.
Function
Afunctionisagroupofreusablecodewhichcanbecalledanywhereinyourprogram.This
eliminatestheneedofwritingsamecodeoverandoveragain.Thiswillenableprogrammers
todivideabigprogramintoanumberofsmallandmanageablefunctions.
Apart from inbuilt Functions, VBA allows us to write userdefined functions as well and
statementsarewrittenbetweenFunctionandEndFunction
SubProcedures
SubProceduresworksimilartofunctionswhileSubproceduresDONOTReturnavaluewhile
functions may or may not return a value. Sub procedures Can be called without call
keyword.SubproceduresarealwaysenclosedwithinSubandEndSubstatements.
CommentsinVBA
Comments are used to document the program logic and the user information with which
otherprogrammerscanseamlesslyworkonthesamecodeinfuture.
It can include information such as developed by, modified by and it can also include
incorporatedlogic.Commentsareignoredbytheinterpreterwhileexecution.
CommentsinVBAaredenotedbytwomethods.
1. Any statement that starts with a Single Quote () is treated as comment.
Followingistheexample:
'ThisScriptisinvokedaftersuccessfullogin
'Writtenby:TutorialsPoint
'ReturnValue:True/False
2.Anystatementthatstartswiththekeyword"REM".Followingistheexample:
REMThisScriptiswrittentoValidatetheEnteredInput
REMModifiedby:Tutorialspoint/user2
WhatisaMessageBox?
The MsgBox function displays a message box and waits for the user to click a button and
thenanactionisperformedbasedonthebuttonclickedbytheuser.
Syntax
MsgBox(prompt[,buttons][,title][,helpfile,context])
ParameterDescription
Prompt A Required Parameter. A String that is displayed as a message in the
dialogbox.Themaximumlengthofpromptisapproximately1024characters.Ifthe
message extends to more than a line, then we can separate the lines using a
carriagereturncharacter(Chr(13))oralinefeedcharacter(Chr(10))betweeneach
line.
buttons An Optional Parameter. A Numeric expression that specifies the type of
buttonstodisplay,theiconstyletouse,theidentityofthedefaultbutton,andthe
modalityofthemessagebox.Ifleftblank,thedefaultvalueforbuttonsis0.
Title An Optional Parameter. A String expression displayed in the title bar of the
dialogbox.Ifthetitleisleftblank,theapplicationnameisplacedinthetitlebar.
helpfileAnOptionalParameter.AStringexpressionthatidentifiestheHelpfileto
usetoprovidecontextsensitivehelpforthedialogbox.
context An Optional Parameter. A Numeric expression that identifies the Help
contextnumberassignedbytheHelpauthortotheappropriateHelptopic.Ifcontext
isprovided,helpfilemustalsobeprovided.
TheButtonsparametercantakeanyofthefollowingvalues:
0vbOKOnlyDisplaysOKbuttononly.
1vbOKCancelDisplaysOKandCancelbuttons.
2vbAbortRetryIgnoreDisplaysAbort,Retry,andIgnorebuttons.
3vbYesNoCancelDisplaysYes,No,andCancelbuttons.
4vbYesNoDisplaysYesandNobuttons.
5vbRetryCancelDisplaysRetryandCancelbuttons.
16vbCriticalDisplaysCriticalMessageicon.
32vbQuestionDisplaysWarningQueryicon.
48vbExclamationDisplaysWarningMessageicon.
64vbInformationDisplaysInformationMessageicon.
0vbDefaultButton1Firstbuttonisdefault.
256vbDefaultButton2Secondbuttonisdefault.
512vbDefaultButton3Thirdbuttonisdefault.
768vbDefaultButton4Fourthbuttonisdefault.
0 vbApplicationModal Application modal. The current application will not work until
theuserrespondstothemessagebox.
4096 vbSystemModal System modal. All applications will not work until the user
respondstothemessagebox.
Theabovevaluesarelogicallydividedintofourgroups:Thefirstgroup(0to5)indicatesthe
buttonstobedisplayedinthemessagebox.Thesecondgroup(16,32,48,64)describes
the sytle of the icon to be displayed, the third group (0, 256, 512, 768) indicates which
buttonmustbethedefault,andthefourthgroup(0,4096)determinesthemodalityofthe
messagebox.
ReturnValues
TheMsgBoxfunctioncanreturnoneofthefollowingvaluesusingwhichwewillbeableto
identifythebuttontheuserhasclickedinthemessagebox.
1vbOKOKwasclicked
2vbCancelCancelwasclicked
3vbAbortAbortwasclicked
4vbRetryRetrywasclicked
5vbIgnoreIgnorewasclicked
6vbYesYeswasclicked
7vbNoNowasclicked
Example
FunctionMessageBox_Demo()
'MessageBoxwithjustpromptmessage
MsgBox("Welcome")
'MessageBoxwithtitle,yesnoandcancelButttons
a=MsgBox("Doyoulikebluecolor?",3,"Chooseoptions")
'AssumethatyoupressNoButton
msgbox("TheValueofais"&a)
EndFunction
Output
1.TheaboveFunctioncanbeexecutedeitherbyclicking"Run"ButtononVBAWindoworby
callingthefunctionfromExcelWorksheetasshownbelow.
2.ASimpleMessageboxisdisplayedwithamessage"Welcome"andan"OK"Button
3.AfterClickingOK,yetanotherdialogboxisdisplayedwithamessageand"yes,no,and
cancel"buttons.
4. After Clicking Cancel button the value of that button(7) is stored as an integer and
displayedasamessageboxtotheuserasshownbelow.Usingthisvaluewewillbeableto
knowwhichbuttonuserhasclicked..
WhatisanInputBox?
The InputBox function helps the user to get the values from the user. After entering the
values, if the user clicks the OK button or presses ENTER on the keyboard, the InputBox
function will return the text in the text box. If the user clicks on the Cancel button, the
functionwillreturnanemptystring("").
Syntax
InputBox(prompt[,title][,default][,xpos][,ypos][,helpfile,context])
ParameterDescription:
Prompt A Required Parameter. A String that is displayed as a message in the
dialogbox.Themaximumlengthofpromptisapproximately1024characters.Ifthe
message extends to more than a line, then we can separate the lines using a
carriagereturncharacter(Chr(13))oralinefeedcharacter(Chr(10))betweeneach
line.
Title An Optional Parameter. A String expression displayed in the title bar of the
dialogbox.Ifthetitleisleftblank,theapplicationnameisplacedinthetitlebar.
DefaultAnOptionalParameter.Adefaulttextinthetextboxthattheuserwould
liketobedisplayed.
XPosAnOptionalParameter.ThePositionofXaxiswhichrepresentstheprompt
distance from left side of the screen horizontally. If left blank, the input box is
horizontallycentered.
YPos An Optional Parameter. The Position of Y axis which represents the prompt
distance from left side of the screen Vertically. If left blank, the input box is
Verticallycentered.
helpfileAnOptionalParameter.AStringexpressionthatidentifiestheHelpfileto
usetoprovidecontextsensitiveHelpforthedialogbox.
Example
Wewillcalculatetheareaofarectanglebygettingvaluesfromtheuseratruntimewiththe
helpoftwoinputboxes(oneforlengthandoneforwidth)
FunctionfindArea()
DimLengthAsDouble
DimWidthAsDouble
Length=InputBox("EnterLength","EnteraNumber")
Width=InputBox("EnterWidth","EnteraNumber")
findArea=Length*Width
EndFunction
Output
1. To Execute the same, we will need to call using the function name and press Enter as
shownbelow.
2.UponExecution,TheFirstInputbox(Length)isdisplayedanduserhastoenteravalue
intotheinputbox.
3.Afterenteringthefirstvalue,thesecondinputbox(width)isdisplayedtotheuser.
4. Upon entering the second number and clicking OK button, the area is displayed to the
userasshownbelow.
Variableisanamedmemorylocationusedtoholdavaluethatcanbechangedduringthe
scriptexecution.Belowarethebasicrulesfornamingavariable.Listedbelowaretherules
fornamingavariable.
Youmustusealetterasthefirstcharacter.
Youcan'tuseaspace,period(.),exclamationmark(!),orthecharacters@,&,$,#
inthename.
Namecan'texceed255charactersinlength.
CannotuseVisualBasicreservedkeywordsasvariablename.
Syntax
InVBA,weneedtodeclarethevariablesbeforeusingthem.
Dim<<variable_name>>As<<variable_type>>
DataTypes
There are many VBA data types, which can be grossly divided into two main categories
namelynumericandnonnumericdatatypes.
NumericDataTypes
Belowtabledisplaysthenumericdatatypesandallowedrangeofvalues.
Type
RangeofValues
Byte
0to255
Integer
32,768to32,767
Long
2,147,483,648to2,147,483,648
Single
Double
Currency
Decimal
3.402823E+38to1.401298E45fornegativevalues
1.401298E45to3.402823E+38forpositivevalues.
1.79769313486232e+308to4.94065645841247E324fornegativevalues
4.94065645841247E324to1.79769313486232e+308forpositivevalues.
922,337,203,685,477.5808to922,337,203,685,477.5807
+/79,228,162,514,264,337,593,543,950,335ifnodecimalisuse
+/7.9228162514264337593543950335(28decimalplaces).
NonNumericDataTypes
BelowtabledisplaystheNonnumericdatatypesandallowedrangeofvalues.
Type
RangeofValues
String(fixedlength)
1to65,400characters
String(variablelength)
0to2billioncharacters
Date
January1,100toDecember31,9999
Boolean
TrueorFalse
Object
Anyembeddedobject
Variant(numeric)
AnyvalueaslargeasDouble
Variant(text)
Sameasvariablelengthstring
Example
Letuscreateabuttonandnameitas'Variables_demo'todemostratetheuseofvariables.
PrivateSubVariables_demo_Click()
DimpasswordAsString
password="Admin#1"
DimnumAsInteger
num=1234
DimBirthDayAsDate
BirthDay=30/10/2020
MsgBox"Passowrdis"&password&Chr(10)&"Valueofnumis"&num&Chr(10)&"ValueofBirthdayis
EndSub
Output
UponExecutingthescript,theoutputwillbeasshownbelow.
ConstantisanamedmemorylocationusedtoholdavaluethatCANNOTbechangedduring
thescriptexecution.IfausertriestochangeaConstantValue,theScriptexecutionendsup
withanerror.Constantsaredeclaredthesamewaythevariablesaredeclared.
Belowaretherulesfornamingaconstant.
Youmustusealetterasthefirstcharacter.
Youcan'tuseaspace,period(.),exclamationmark(!),orthecharacters@,&,$,#
inthename.
Namecan'texceed255charactersinlength.
CannotuseVisualBasicreservedkeywordsasvariablename.
Syntax
InVBA,weneedtoassignavaluetothedeclaredConstants.Errorwouldbethrownifwetry
tochangethevalueoftheconstant.
Const<<constant_name>>As<<constant_type>>=<<constant_value>>
Example
Wewillcreateabutton"Constant_demo"todemonstratehowtoworkwithconstants.
PrivateSubConstant_demo_Click()
ConstMyIntegerAsInteger=42
ConstmyDateAsDate=#2/2/2020#
ConstmyDayAsString="Sunday"
MsgBox"Integeris"&MyInteger&Chr(10)&"myDateis"&myDate&Chr(10)&"myDayis"&myDay
EndSub
Output
Uponexecutingthescript,theoutputwillbedisplayedasshownbelow.
Whatisanoperator?
Simpleanswercanbegivenusingexpression4+5isequalto9.Here,4and5arecalled
operandsand+iscalledoperator.VBAsupportsfollowingtypesofoperators:
ArithmeticOperators
ComparisonOperators
Logical(orRelational)Operators
ConcatenationOperators
TheArithmaticOperators
TherearefollowingarithmaticoperatorssupportedbyVBA:
AssumevariableAholds5andvariableBholds10,then:
ShowExamples
Operator Description
Example
Addstwooperands
A+Bwillgive15
Subtractssecondoperandfromthefirst
ABwillgive5
Multiplybothoperands
A*Bwillgive50
Dividenumeratorbydenumerator
B/Awillgive2
ModulusOperatorandremainderofafteranintegerdivision
BMODAwillgive0
ExponentiationOperator
B^Awillgive100000
TheComparisonOperators
TherearefollowingcomparisonoperatorssupportedbyVBA:
AssumevariableAholds10andvariableBholds20,then:
ShowExamples
Operator Description
==
<>
>
<
>=
<=
Example
Checksifthevalueoftwooperandsareequalornot,ifyesthencondition (A==B)
becomestrue.
isFalse.
Checksifthevalueoftwooperandsareequalornot,ifvaluesarenot
(A<>B)
equalthenconditionbecomestrue.
isTrue.
Checksifthevalueofleftoperandisgreaterthanthevalueofright
(A>B)is
operand,ifyesthenconditionbecomestrue.
False.
Checksifthevalueofleftoperandislessthanthevalueofrightoperand, (A<B)is
ifyesthenconditionbecomestrue.
True.
Checksifthevalueofleftoperandisgreaterthanorequaltothevalueof
(A>=B)
rightoperand,ifyesthenconditionbecomestrue.
isFalse.
Checksifthevalueofleftoperandislessthanorequaltothevalueof
(A<=B)
rightoperand,ifyesthenconditionbecomestrue.
isTrue.
TheLogicalOperators:
TherearefollowinglogicaloperatorssupportedbyVBA:
AssumevariableAholds10andvariableBholds0,then:
ShowExamples
Operator Description
AND
OR
NOT
XOR
Example
CalledLogicalANDoperator.IfboththeconditionsareTruethen
Expressionbecomestrue.
a<>0AND
b<>0is
False.
CalledLogicalOROperator.IfanyofthetwoconditionsareTruethen a<>0OR
conditionbecomestrue.
b<>0istrue.
CalledLogicalNOTOperator.Usetoreversesthelogicalstateofits
NOT(a<>0
operand.IfaconditionistruethenLogicalNOToperatorwillmake
ORb<>0)is
false.
false.
CalledLogicalExclusion.ItisthecombinationofNOTandOR
(a<>0XOR
Operator.Ifone,andonlyone,oftheexpressionsevaluatestoTrue,
b<>0)is
resultisTrue.
false.
TheConcatenationOperators
TherearefollowingConcatenationoperatorssupportedbyVBA:
AssumevariableAholds5andvariableBholds10then:
ShowExamples
Operator
Description
Example
AddstwoValuesasVariableValuesareNumeric
A+Bwillgive15
&
ConcatenatestwoValues
A&Bwillgive510
AssumevariableA="Microsoft"andvariableB="VBScript",then:
Operator
Description
Example
ConcatenatestwoValues
A+BwillgiveMicrosoftVBScript
&
ConcatenatestwoValues
A&BwillgiveMicrosoftVBScript
Note : Concatenation Operators can be used for both numbers and strings. The Output
dependsonthecontextifthevariablesholdnumericvalueorStringValue.
Decisionmakingallowsprogrammerstocontroltheexecutionflowofascriptoroneofits
sections.Theexecutionisgovernedbyoneormoreconditionalstatements.
Following is the general form of a typical decision making structure found in most of the
programminglanguages:
VBA provides following types of decision making statements. Click the following links to
checktheirdetails.
Statement
ifstatement
Description
Anifstatementconsistsofabooleanexpressionfollowedby
oneormorestatements.
Anifelsestatementconsistsofabooleanexpressionfollowed
if..elsestatement
byoneormorestatements.IftheconditionisTrue,the
statementsunderIfstatementsareexecuted.Ifthecondition
isfalse,ElsepartofthescriptisExecuted
AnifstatementfollowedbyoneormoreElseIfStatements,
if...elseif..elsestatement
thatconsistsofbooleanexpressionsandthenfollowedbyan
optionalelsestatement,whichexecuteswhenallthe
conditionbecomesfalse.
nestedifstatements
switchstatement
Aniforelseifstatementinsideanotheriforelseif
statement(s).
Aswitchstatementallowsavariabletobetestedforequality
againstalistofvalues.
There may be a situation when you need to execute a block of code several number of
times.Ingeneral,statementsareexecutedsequentially:Thefirststatementinafunctionis
executedfirst,followedbythesecond,andsoon.
Programminglanguagesprovidevariouscontrolstructuresthatallowformorecomplicated
executionpaths.
Aloopstatementallowsustoexecuteastatementorgroupofstatementsmultipletimes
andfollowingisthegeneralfromofaloopstatementinVBA.
VBAprovidesthefollowingtypesofloopstohandleloopingrequirements.Clickthefollowing
linkstochecktheirdetail.
LoopType
forloop
for..eachloop
while..wendloop
do..whileloops
do..untilloops
Description
Executesasequenceofstatementsmultipletimesandabbreviates
thecodethatmanagestheloopvariable.
Thisisexecutedifthereisatleastoneelementingroupand
reiteratedforeachelementinagroup.
Thisteststheconditionbeforeexecutingtheloopbody.
Thedo..Whilestatementswillbeexecutedaslongasconditionis
True.(i.e.,)TheLoopshouldberepeatedtilltheconditionisFalse.
Thedo..Untilstatementswillbeexecutedaslongasconditionis
False.(i.e.,)TheLoopshouldberepeatedtilltheconditionisTrue.
LoopControlStatements:
Loop control statements change execution from its normal sequence. When execution
leavesascope,alltheremainingstatementsintheloopareNOTexecuted.
VBAsupportsthefollowingcontrolstatements.Clickthefollowinglinkstochecktheirdetail.
ControlStatement
ExitForstatement
ExitDostatement
Description
TerminatestheForloopstatementandtransfersexecutiontothe
statementimmediatelyfollowingtheloop
TerminatestheDoWhilestatementandtransfersexecutionto
thestatementimmediatelyfollowingtheloop
Stringsareasequenceofcharacters,whichcanconsistofalphabetsornumbersorspecial
characters or all of them. A variable is said to be a string if it is enclosed within double
quotes"".
Syntax:
variablename="string"
Examples:
str1="string"'OnlyAlphabets
str2="132.45"'OnlyNumbers
str3="!@#$;*"'OnlySpecialCharacters
Str4="Asc23@#"'Hasalltheabove
StringFunctions:
There are predefined VBA String functions, which help the developers to work with the
stringsveryeffectively.BelowareStringmethodsthataresupportedinVBA.Pleaseclickon
eachoneofthemethodstoknowindetail.
Function
Name
InStr
InstrRev
Description
Returnsthefirstoccurenceofthespecifiedsubstring.Searchhappensfromleft
toright.
Returnsthefirstoccurenceofthespecifiedsubstring.Searchhappensfrom
RighttoLeft.
Lcase
Returnsthelowercaseofthespecifiedstring.
Ucase
ReturnstheUppercaseofthespecifiedstring.
Left
Returnsaspecificnumberofcharactersfromtheleftsideofthestring.
Right
Mid
Ltrim
Rtrim
ReturnsaspecificnumberofcharactersfromtheRightsideofthestring.
Returnsaspecificnumberofcharactersfromastringbasedonthespecified
parameters.
Returnsastringafterremovingthespacesontheleftsideofthespecified
string.
Returnsastringafterremovingthespacesontherightsideofthespecified
string.
Trim
Returnsastringvalueafterremovingbothleadingandtrailingblankspaces.
Len
Returnsthelenghtofthegivenstring.
Replace
Returnsastringafterreplacingastringwithanotherstring.
Space
Fillsastringwiththespecifiednumberofspaces.
StrComp
Returnsanintegervalueaftercomparingthetwospecifiedstrings.
String
ReturnsaStringwithaspecifiedcharacterthespecifiednumberoftimes.
StrReverse
ReturnsaStringafterreversingthesequeceofthecharactersofthegiven
string.
VBScriptDateandTimeFunctionshelpthedeveloperstoconvertdateandtimefromone
format to another or to express the date or time value in the format that suits a specific
condition.
DateFunctions
Function
Description
Date
AFunction,whichreturnsthecurrentsystemdate
CDate
AFunction,whichconvertsagiveninputtoDate
DateAdd
AFunction,whichreturnsadatetowhichaspecifiedtimeintervalhas
beenadded
DateDiff
AFunction,whichreturnsthedifferencebetweentwotimeperiod
DatePart
AFunction,whichreturnsaspecifiedpartofthegiveninputdatevalue
DateSerial
AFunction,whichreturnsavaliddateforthegivenyear,monthanddate
FormatDateTime
AFunction,whichformatsthedatebasedonthesuppliedparameters
IsDate
AFunction,whichreturnsaBooleanValuewhetherornotthesupplied
parameterisadate
AFunction,whichreturnsanintegerbetween1and31thatrepresents
Day
Month
Year
MonthName
WeekDay
WeekDayName
thedayofthespecifiedDate
AFunction,whichreturnsanintegerbetween1and12thatrepresents
themonthofthespecifiedDate
AFunction,whichreturnsanintegerthatrepresentstheyearofthe
specifiedDate
AFunction,whichreturnsNameoftheparticularmonthforthespecifed
date
AFunction,whichreturnsaninteger(1to7)thatrepresentsthedayof
theweekforthespecifiedday.
AFunction,whichreturnstheweekdaynameforthespecifiedday.
TimeFunctions
Function
Description
Now
AFunction,whichreturnsthecurrentsystemdateandTime
Hour
Minute
Second
Time
Timer
TimeSerial
TimeValue
AFunction,whichreturnsandintegerbetween0and23thatrepresentsthe
Hourpartofthethegiventime
AFunction,whichreturnsandintegerbetween0and59thatrepresentsthe
Minutespartofthethegiventime
AFunction,whichreturnsandintegerbetween0and59thatrepresentsthe
Secondspartofthethegiventime
AFunction,whichreturnsthecurrentsystemtime
AFunction,whichreturnsthenumberofsecondsandmillisecondssince
12:00AM
AFunction,whichreturnsthetimeforthespecificinputofhour,minuteand
second
AFunction,whichconvertstheinputstringtoatimeformat
WhatisanArray?
Weknowverywellthatavariableisacontainertostoreavalue.Sometimes,developers
areinapositiontoholdmorethanonevalueinasinglevariableatatime.Whenaseriesof
valuesarestoredinasinglevariable,thenitisknownasarrayvariable.
ArrayDeclaration
Arraysaredeclaredthesamewayavariablehasbeendeclaredexceptthatthedeclaration
of an array variable uses paranthesis. In the below example, the size of the array is
mentionedinthebrackets.
'Method1:UsingDim
Dimarr1()
'WithoutSize
'Method2:MentioningtheSize
Dimarr2(5)'Declaredwithsizeof5
'Method3:using'Array'Parameter
Dimarr3
arr3=Array("apple","Orange","Grapes")
1. Although, the Array size is indicated as 5, it can hold 6 values as array index starts
fromZERO.
2. ArrayIndexCannotbeNegative.
3. VBScriptArrayscanstoreanytypeofvariableinanarray.Hence,anarraycanstore
aninteger,stringorcharactersinasinglearrayvariable.
AssigningValuestoanArray
Thevaluesareassignedtothearraybyspecifyingarrayindexvalueagainsteachoneofthe
valuestobeassigned.Itcanbeastring.
Example:
Addabuttonandaddthebelowfunction
PrivateSubConstant_demo_Click()
Dimarr(5)
arr(0)="1"'NumberasString
arr(1)="VBScript"'String
arr(2)=100
'Number
arr(3)=2.45
'DecimalNumber
arr(4)=#10/07/2013#'Date
arr(5)=#12.45PM#'Time
msgbox("ValuestoredinArrayindex0:"&arr(0))
msgbox("ValuestoredinArrayindex1:"&arr(1))
msgbox("ValuestoredinArrayindex2:"&arr(2))
msgbox("ValuestoredinArrayindex3:"&arr(3))
msgbox("ValuestoredinArrayindex4:"&arr(4))
msgbox("ValuestoredinArrayindex5:"&arr(5))
EndSub
Whenyouexecutethefunctiontheoutputisshownbelow:
ValuestoredinArrayindex0:1
ValuestoredinArrayindex1:VBScript
ValuestoredinArrayindex2:100
ValuestoredinArrayindex3:2.45
ValuestoredinArrayindex4:7/10/2013
ValuestoredinArrayindex5:12:45:00PM
MultiDimensionArrays
Arraysarenotjustlimitedtosingledimenstionandcanhaveamaxinumof60dimensions.
Twodimensionarraysarethemostcommonlyusedones.
Example:
Inthebelowexample,amultidimensionarrayisdeclaredwith3rowsand4columns.
PrivateSubConstant_demo_Click()
Dimarr(2,3)asVariant
'Whichhas3rowsand4columns
arr(0,0)="Apple"
arr(0,1)="Orange"
arr(0,2)="Grapes"
arr(0,3)="pineapple"
arr(1,0)="cucumber"
arr(1,1)="beans"
arr(1,2)="carrot"
arr(1,3)="tomato"
arr(2,0)="potato"
arr(2,1)="sandwitch"
arr(2,2)="coffee"
arr(2,3)="nuts"
msgbox("ValueinArrayindex0,1:"&arr(0,1))
msgbox("ValueinArrayindex2,2:"&arr(2,2))
EndSub
Whenyouexecutethefunctiontheoutputisshownbelow:
ValuestoredinArrayindex:0,1:Orange
ValuestoredinArrayindex:2,2:coffee
RedimStatement
ReDim Statement is used to Declare dynamicarray variables and allocate or reallocate
storagespace.
ReDim[Preserve]varname(subscripts)[,varname(subscripts)]
Example
Inthebelowexample,anarrayhasbeenredefinedandthenpreservedthevalueswhenthe
existingsizeofthearrayischanged.
Note : Upon resizing an array smaller than it was originally, the data in the eliminated
elementswillbelost.
PrivateSubConstant_demo_Click()
Dima()asvariant
i=0
redima(5)
a(0)="XYZ"
a(1)=41.25
a(2)=22
REDIMPRESERVEa(7)
Fori=3to7
a(i)=i
Next
'toFetchtheoutput
Fori=0toubound(a)
Msgboxa(i)
Next
EndSub
Whenyouexecutethefunctiontheoutputisshownbelow:
XYZ
41.25
22
3
4
5
6
7
ArrayMethods:
There are various inbuilt functions within VBScript which help the developers to handle
arrayseffectively.Allthemethodsthatareusedinconjuctionwitharraysarelistedbelow.
Pleaseclickonthemethodnametoknowindetail.
Function
LBound
UBound
Split
Join
Filter
IsArray
Erase
Description
AFunction,whichreturnsanintegerthatcorrespondstothesmallest
subscriptofthegivenarrays.
AFunction,whichreturnsanintegerthatcorrespondstotheLargest
subscriptofthegivenarrays.
AFunction,whichreturnsanarraythatcontainsaspecifiednumberof
values.SplittedbasedonaDelimiter.
AFunction,whichreturnsaStringthatcontainsaspecifiednumberof
substringsinanarray.ThisisanexactoppositefunctionofSplitMethod.
AFunction,whichreturnsazerobasedarraythatcontainsasubsetofa
stringarraybasedonaspecificfiltercriteria.
AFunction,whichreturnsabooleanvaluethatindicateswhetherornotthe
inputvariableisanarray.
AFunction,whichrecoverstheallocatedmemoryforthearrayvariables.
WhatisaFunction?
Afunctionisagroupofreusablecodewhichcanbecalledanywhereinyourprogram.This
eliminatestheneedofwritingsamecodeoverandoveragain.Thiswillenableprogrammers
todivideabigprogramintoanumberofsmallandmanageablefunctions.
Apart from inbuilt Functions, VBA allows us to write userdefined functions as well. This
sectionwillexplainyouhowtowriteyourownfunctionsinVBA.
FunctionDefinition
AVBAfunctioncanhaveanoptionalreturnstatement.Thisisrequiredifyouwanttoreturn
avaluefromafunction.
For example, you can pass two numbers in a function and then you can expect from the
functiontoreturntheirmultiplicationinyourcallingprogram.
NOTE:Afunctioncanreturnmultiplevaluesseparatedbycommaasanarrayassignedto
thefunctionnameitself.
Beforeweuseafunction,weneedtodefinethatparticularfunction.Themostcommonway
todefineafunctioninVBAisbyusingtheFunctionkeyword,followedbyauniquefunction
name and it may or may not carry a list of parameters and a statement with a End
Function keyword, which indicates the end of the function. The basic syntax is shown
below:
Syntax
Addabuttonandaddthebelowfunction
FunctionFunctionname(parameterlist)
statement1
statement2
statement3
.......
statementn
EndFunction
Example
Add the below function which returns the area. Note that a value/values can be returned
withthefunctionnameitself.
FunctionfindArea(LengthAsDouble,OptionalWidthAsVariant)
IfIsMissing(Width)Then
findArea=Length*Length
Else
findArea=Length*Width
EndIf
EndFunction
CallingaFunction
Toinvokeafunction,callthefunctionusingfunctionnameasshownbelow:
TheOutputoftheareawouldbedisplayedtotheuser.
SubProcedures
SubProceduresaresimilartofunctionsbuttherearefewdifferences.
Sub procedures DONOT Return a value while functions may or may not return a
value.
SubproceduresCanbecalledwithoutcallkeyword.
SubproceduresarealwaysenclosedwithinSubandEndSubstatements.
Example:
SubArea(xAsDouble,yAsDouble)
MsgBoxx*y
EndSub
CallingProcedures:
ToinvokeaProceduresomewhereinthescript,youcanmakeacallfromafunction.Wewill
notbeabletousethesamewayasthatofafunctionassubprocedureWILLNOTreturna
value.
FunctionfindArea(LengthAsDouble,WidthAsVariant)
areaLength,Width'ToCalculateArea'area'subprociscalled
EndFunction
1.Nowwewillbeabletocallthefunctiononlybutnotthesubprocedureasshownbelow.
2.TheAreaiscalculatedandshownonlyinMessagebox.
3. The result cell displays ZERO as the area value is NOT returned from the function. In
short,youcannotmakeadirectcalltoasubprocedurefromtheexcelworksheet.
VBAEvents
VBA,aneventdrivenprogrammingcanbetriggeredwhenyouchangeacellorrangeofcells
valuemanually.ChangeEventmaymakethingseasier,butyoucanveryquicklyendupa
pagefullofformatting.Therearetwokindsofevents.
WorksheetEvents
WorkbookEvents
WorkSheetEvents
WorksheetEventsaretriggeredwhenthereisachangeintheworksheet.Itiscreatedby
performingrightclickonthesheettabandchoosing'viewcode',andthenpastingthecode.
Usercanselecteachoneofthoseworksheetsandchoose"WorkSheet"fromthedropdown
togetthelistofallsupportedWorksheetevents.
Belowarethesupportedworksheeteventsthatcanbeaddedbytheuser.
PrivateSubWorksheet_Activate()
PrivateSubWorksheet_BeforeDoubleClick(ByValTargetAsRange,CancelAsBoolean)
PrivateSubWorksheet_BeforeRightClick(ByValTargetAsRange,CancelAsBoolean)
PrivateSubWorksheet_Calculate()
PrivateSubWorksheet_Change(ByValTargetAsRange)
PrivateSubWorksheet_Deactivate()
PrivateSubWorksheet_FollowHyperlink(ByValTargetAsHyperlink)
PrivateSubWorksheet_SelectionChange(ByValTargetAsRange)
Example
Letussay,wejustneedtodisplayamessagebeforedoubleclick.
PrivateSubWorksheet_BeforeDoubleClick(ByValTargetAsRange,CancelAsBoolean)
MsgBox"BeforeDoubleClick"
EndSub
Output
Upondoubleclickingonanycell,themessageboxisdisplayedtotheuserasshownbelow.
WorkbookEvents
Workbookeventsaretriggeredwhenthereisachangetotheworkbookonthewhole.We
can add the code for workbook events by selecting the 'ThisWorkbook' and selecting
'workbook'fromthedropdownasshownbelow.ImmediatelyWorkbook_opensubprocedure
isdisplayedtotheuserasshownbelow.
BelowarethesupportedWorkBookeventsthatcanbeaddedbytheuser.
PrivateSubWorkbook_AddinUninstall()
PrivateSubWorkbook_BeforeClose(CancelAsBoolean)
PrivateSubWorkbook_BeforePrint(CancelAsBoolean)
PrivateSubWorkbook_BeforeSave(ByValSaveAsUIAsBoolean,CancelAsBoolean)
PrivateSubWorkbook_Deactivate()
PrivateSubWorkbook_NewSheet(ByValShAsObject)
PrivateSubWorkbook_Open()
PrivateSubWorkbook_SheetActivate(ByValShAsObject)
PrivateSubWorkbook_SheetBeforeDoubleClick(ByValShAsObject,ByValTargetAsRange,CancelAsBoolean
PrivateSubWorkbook_SheetBeforeRightClick(ByValShAsObject,ByValTargetAsRange,CancelAsBoolean
PrivateSubWorkbook_SheetCalculate(ByValShAsObject)
PrivateSubWorkbook_SheetChange(ByValShAsObject,ByValTargetAsRange)
PrivateSubWorkbook_SheetDeactivate(ByValShAsObject)
PrivateSubWorkbook_SheetFollowHyperlink(ByValShAsObject,ByValTargetAsHyperlink)
PrivateSubWorkbook_SheetSelectionChange(ByValShAsObject,ByValTargetAsRange)
PrivateSubWorkbook_WindowActivate(ByValWnAsWindow)
PrivateSubWorkbook_WindowDeactivate(ByValWnAsWindow)
PrivateSubWorkbook_WindowResize(ByValWnAsWindow)
Example
Let us say, we just need to display a message to the user that a new sheet is created
succesfullywheneveranewsheetiscreated.
PrivateSubWorkbook_NewSheet(ByValShAsObject)
MsgBox"NewSheetCreatedSuccessfully"
EndSub
Output
Uponcreatinganewexcelsheetamessageisdisplayedtotheuserasshownbelow.
Therearethreetypesoferrorsinprogramming:(a)SyntaxErrorsand(b)RuntimeErrors
(c)LogicalErrors.
Syntaxerrors
Syntax errors, also called parsing errors, occur at interpretation time for VBScript. For
example, the following line causes a syntax error because it is missing a closing
parenthesis:
FunctionErrorHanlding_Demo()
dimx,y
x="Tutorialspoint"
y=Ucase(x
EndFunction
Runtimeerrors
Runtimeerrors,alsocalledexceptions,occurduringexecution,afterinterpretation.
Forexample,thefollowinglinecausesaruntimeerrorbecauseheresyntaxiscorrectbutat
runtimeitistryingtocallfnmultiply,whichisanonexistingfunction:
FunctionErrorHanlding_Demo1()
Dimx,y
x=10
y=20
z=fnadd(x,y)
a=fnmultiply(x,y)
EndFunction
Functionfnadd(x,y)
fnadd=x+y
EndFunction
Logicalerrors
Logicerrorscanbethemostdifficulttypeoferrorstotrackdown.Theseerrorsarenotthe
result of a syntax or runtime error. Instead, they occur when you make a mistake in the
logicthatdrivesyourscriptandyoudonotgettheresultyouexpected.
Youcannotcatchthoseerrors,becauseitdependsonyourbusinessrequirementwhattype
oflogicyouwanttoputinyourprogram.
Forexample,dividinganumberbyzeroorascriptthatiswrittenwhichentersintoinfinite
loop.
ErrObject
Assume if we have a runtime error, then the execution stops by displaying the error
message.Asadeveloper,ifwewanttocapturetheerror,thenErrorObjectisused.
Example
Inthebelowexample,Err.NumbergivestheerrornumberandErr.Descriptiongiveserror
description.
Err.Raise6'Raiseanoverflowerror.
MsgBox"Error#"&CStr(Err.Number)&""&Err.Description
Err.Clear'Cleartheerror.
ErrorHandling
VBA Enables an errorhandling routine and can also be used to disable an errorhandling
routine. Without an On Error statement, any runtime error that occurs is fatal: an error
messageisdisplayed,andexecutionstopsabruptly.
OnError{GoTo[line|0|1]|ResumeNext}
Keyword Description
Enablestheerrorhandlingroutinethatstartsatthelinespecifiedintherequired
GoToline
lineargument.ThespecifiedlinemustbeinthesameprocedureastheOnError
statement,oracompiletimeerrorwilloccur.
GoTo0
DisablesenablederrorhandlerinthecurrentprocedureandresetsittoNothing.
GoTo1
DisablesenabledexceptioninthecurrentprocedureandresetsittoNothing.
Resume
Next
Specifiesthatwhenaruntimeerroroccurs,controlgoestothestatement
immediatelyfollowingthestatementwheretheerroroccurred,andexecution
continuesfromthatpoint
EXAMPLE
PublicSubOnErrorDemo()
OnErrorGoToErrorHandler'Enableerrorhandlingroutine.
Dimx,y,zAsInteger
x=50
y=0
z=x/y'DividebyZEROErrorRaises
ErrorHandler:'Errorhandlingroutine.
SelectCaseErr.Number'Evaluateerrornumber.
Case10'Dividebyzeroerror
MsgBox("Youattemptedtodividebyzero!")
CaseElse
MsgBox"UNKNOWNERRORError#"&Err.Number&":"&Err.Description
EndSelect
ResumeNext
EndSub
WhatareExcelObjects
WhenprogrammingusingVBA,therearefewimportantobjectsthatauserwouldbedealing
with.
ApplicationObjects
WorkBookObjects
WorkSheetObjects
RangeObjects
ApplicationObjects
TheApplicationobjectconsistsofthefollowing
Applicationwidesettingsandoptions.
Methodsthatreturntoplevelobjects,suchasActiveCell,ActiveSheet,andsoon.
Example
'Example1:
Setxlapp=CreateObject("Excel.Sheet")
xlapp.Application.Workbooks.Open"C:\test.xls"
'Example2:
Application.Windows("test.xls").Activate
'Example3:
Application.ActiveCell.Font.Bold=True
WorkBookObjects
The Workbook object is a member of the Workbooks collection and contains all the
WorkbookobjectscurrentlyopeninMicrosoftExcel.
Example
'Ex1:TocloseWorkbooks
Workbooks.Close
'Ex2:ToAddanEmptyWorkBook
Workbooks.Add
'Ex3:ToOpenaWorkbook
Workbooks.OpenFileName:="Test.xls",ReadOnly:=True
'Ex:4ToActivateWorkBooks
Workbooks("Test.xls").Worksheets("Sheet1").Activate
WorksheetObjects
The Worksheet object is a member of the Worksheets collection and contains all the
Worksheetobjectsinaworkbook.
Example
'Ex1:TomakeitInvisible
Worksheets(1).Visible=False
'Ex2:ToprotectanWorkSheet
Worksheets("Sheet1").Protectpassword:=strPassword,scenarios:=True
RangeObjects
Range Objects Represents a cell, a row, a column, a selection of cells containing one or
morecontinuousblocksofcells.
'Ex1:ToPutavalueinthecellA5
Worksheets("Sheet1").Range("A5").Value="5235"
'Ex2:ToputavalueinrangeofCells
Worksheets("Sheet1").Range("A1:A4").Value=5
VBATextFiles
WecanalsoreadExcelFileandwritethecontentsofthecellintoaTextFile.Thisway,VBA
allowsuserstoworkwithtextfiles.Wecanworkwithtestfilesusingtwomethods
FileSystemObject
usingWriteCommand
UsingFileSystemObject(FSO)
As the name suggests, FSO Objects help the developers to work with drives, folders and
files.Inthissection,wewilldiscusshowtouseFSO.
ObjectType
Drive
Drives
File
Files
Description
DriveisanObject.Containsmethodsandpropertiesthatallowyoutogather
informationaboutadriveattachedtothesystem
DrivesisaCollection.ItProvidesalistofthedrivesattachedtothesystem,
eitherphysicallyorlogically.
FileisanObject.ItContainsmethodsandpropertiesthatallowdevelopers
tocreate,deleteormoveafile.
FilesisaCollection.ItProvidesalistofallfilescontainedwithinafolder.
Folder
FolderisanObject.ItProvidesmethodsandpropertiesthatallowdevelopers
tocreate,deleteormovefolders.
Folders
FoldersisaCollection.ItProvidesalistofallthefolderswithinaFolder.
TextStream
TextStreamisanObject.Itenablesdeveloperstoreadandwritetextfiles.
Drive
Drive is an object, which provides access to the properties of a particular disk drive or
networkshare.TheFollowingpropertiesaresupportedbyDriveobject:
AvailableSpace
DriveLetter
DriveType
FileSystem
FreeSpace
IsReady
Path
RootFolder
SerialNumber
ShareName
TotalSize
VolumeName
Example
Step 1 : Before proceeding to scripting using FSO, we should enable Microsoft Scripting
Runtime.Todothesame,Navigateto"Tools">>"References"asshownbelow:
Step2:Add"MicrosoftScriptingRunTime"andClickOK.
Step3:AddDatathatyouwouldliketowriteittoaTextFileandaddaCommandButton.
Step4:NowitistimetoScript.
PrivateSubfn_write_to_text_Click()
DimFilePathAsString
DimCellDataAsString
DimLastColAsLong
DimLastRowAsLong
DimfsoAsFileSystemObject
Setfso=NewFileSystemObject
DimstreamAsTextStream
LastCol=ActiveSheet.UsedRange.Columns.Count
LastRow=ActiveSheet.UsedRange.Rows.Count
'CreateaTextStream.
Setstream=fso.OpenTextFile("D:\Try\Support.log",ForWriting,True)
CellData=""
Fori=1ToLastRow
Forj=1ToLastCol
CellData=Trim(ActiveCell(i,j).Value)
stream.WriteLine"TheValueatlocation("&i&","&j&")"&CellData
Nextj
Nexti
stream.Close
MsgBox("JobDone")
EndSub
Output
Whenexecutingthescript,ensurethatyouplacethecursorinthefirstcelloftheworksheet.
TheSupport.logfileiscreatedasshownbelowunder"D:\Try".
TheContentsofthefileisalsoshownbelow:
UsingWriteCommand
unlikeFSO,weneedNOTaddanyreferences,howeverwewillNOTbeabletoworkDrives,
FilesandFolders.Wewillbeabletojustaddthestreamtotextfile.
Example
PrivateSubfn_write_to_text_Click()
DimFilePathAsString
DimCellDataAsString
DimLastColAsLong
DimLastRowAsLong
LastCol=ActiveSheet.UsedRange.Columns.Count
LastRow=ActiveSheet.UsedRange.Rows.Count
FilePath="D:\Try\write.txt"
OpenFilePathForOutputAs#2
CellData=""
Fori=1ToLastRow
Forj=1ToLastCol
CellData="TheValueatlocation("&i&","&j&")"&Trim(ActiveCell(i,j).Value)
Write#2,CellData
Nextj
Nexti
Close#2
MsgBox("JobDone")
EndSub
Output
Upon executing the script, the "write.txt" file is created in the location "D:\Try" as shown
below.
TheContentsofthefileisalsoshownbelow:
VBAProgrammingCharts
UsingVBA,wewillbeabletodogenerateChartsbasedoncertaincriteria.Letustakealook
atitwithanexample.
Step1:FirstEnterthedataagainstwhichthegraphhastobegenerated.
Step2:Letuscreate3buttonsonetogenerateBargraph,pieChart,ColumnChart.
Step3:NowletusdevelopaMacrotogenerateeachoneofthesetypeofcharts
'ProceduretoGeneratePieChart
PrivateSubfn_generate_pie_graph_Click()
DimchtAsChartObject
ForEachchtInWorksheets(1).ChartObjects
cht.Chart.Type=xlPie
Nextcht
EndSub
'ProceduretoGenerateBarGraph
PrivateSubfn_Generate_Bar_Graph_Click()
DimchtAsChartObject
ForEachchtInWorksheets(1).ChartObjects
cht.Chart.Type=xlBar
Nextcht
EndSub
'ProceduretoGenerateColumnGraph
PrivateSubfn_generate_column_graph_Click()
DimchtAsChartObject
ForEachchtInWorksheets(1).ChartObjects
cht.Chart.Type=xlColumn
Nextcht
EndSub
Step 4 : Upon clicking on the corresponding button, that chart is created. In the below
outputwehaveclickedongeneratePieChartbutton.
VBAUserForms
AUserFormisacustombuiltdialogboxthatmakesauserdataentrymorecontrollablefor
youandeasierfortheuser.Inthischapter,wewilldesignaSimpleformandadddatainto
excel.
Step1:NavigatetoVBAWindowbypressingAlt+F11andNavigateto"Insert"Menuand
select"UserForm".Uponselecting,userformisdisplayedbelow.
Step2:Nowletusdesigntheformsusingthegivencontrols.
Step3:Afteraddingeachcontrols,thecontrolshastobenamed.Captioncorrespondsto
whatappearsontheformandnamecorrespondstothelogicalnamewhichwillbeappearing
whilewewriteVBAcodeforthatelement.
Step4:Belowarenamesagainsteachoneoftheaddedcontrols.
Control
LogicalName
Caption
From
frmempform
EmployeeForm
EmployeeIDLabelBox
empid
EmployeeID
firstnameLabelBox
firstname
FirstName
lastnameLabelBox
lastname
LastName
dobLabelBox
dob
DateofBirth
mailidLabelBox
mailid
EmailID
PassportholderLabelBox
Passportholder
PassportHolder
EmpIDTextBox
txtempid
NOTApplicable
FirstNameTextBox
txtfirstname
NOTApplicable
LastNameTextBox
txtlastname
NOTApplicable
EmailIDTextBox
txtemailid
NOTApplicable
DateComboBox
cmbdate
NOTApplicable
MonthComboBox
cmbmonth
NOTApplicable
YearComboBox
cmbyear
NOTApplicable
YesRadioButton
radioyes
Yes
NoRadioButton
radiono
No
SubmitButton
btnsubmit
Submit
CancelButton
btncancel
Cancel
Step5:Nowwewilladdcodefortheformloadeventbyperformingrightclickontheform
andselecting'ViewCode'.
Step6:Selectuserformfromtheobjectsdropdownandselect'Initialize'methodasshown
below.
Step 7 : Upon Loading the Form we should ensure that the text boxes are cleared, Drop
downboxesarefilledandRadiobuttonsareresetted
PrivateSubUserForm_Initialize()
'EmptyEmpIDTextboxandSettheCursor
txtempid.Value=""
txtempid.SetFocus
'Emptyallothertextboxfields
txtfirstname.Value=""
txtlastname.Value=""
txtemailid.Value=""
'ClearAllDateofBirthRelatedFields
cmbdate.Clear
cmbmonth.Clear
cmbyear.Clear
'FillDateDropDownboxTakes1to31
Withcmbdate
.AddItem"1"
.AddItem"2"
.AddItem"3"
.AddItem"4"
.AddItem"5"
.AddItem"6"
.AddItem"7"
.AddItem"8"
.AddItem"9"
.AddItem"10"
.AddItem"11"
.AddItem"12"
.AddItem"13"
.AddItem"14"
.AddItem"15"
.AddItem"16"
.AddItem"17"
.AddItem"18"
.AddItem"19"
.AddItem"20"
.AddItem"21"
.AddItem"22"
.AddItem"23"
.AddItem"24"
.AddItem"25"
.AddItem"26"
.AddItem"27"
.AddItem"28"
.AddItem"29"
.AddItem"30"
.AddItem"31"
EndWith
'FillMonthDropDownboxTakesJantoDec
Withcmbmonth
.AddItem"JAN"
.AddItem"FEB"
.AddItem"MAR"
.AddItem"APR"
.AddItem"MAY"
.AddItem"JUN"
.AddItem"JUL"
.AddItem"AUG"
.AddItem"SEP"
.AddItem"OCT"
.AddItem"NOV"
.AddItem"DEC"
EndWith
'FillYearDropDownboxTakes1980to2014
Withcmbyear
.AddItem"1980"
.AddItem"1981"
.AddItem"1982"
.AddItem"1983"
.AddItem"1984"
.AddItem"1985"
.AddItem"1986"
.AddItem"1987"
.AddItem"1988"
.AddItem"1989"
.AddItem"1990"
.AddItem"1991"
.AddItem"1992"
.AddItem"1993"
.AddItem"1994"
.AddItem"1995"
.AddItem"1996"
.AddItem"1997"
.AddItem"1998"
.AddItem"1999"
.AddItem"2000"
.AddItem"2001"
.AddItem"2002"
.AddItem"2003"
.AddItem"2004"
.AddItem"2005"
.AddItem"2006"
.AddItem"2007"
.AddItem"2008"
.AddItem"2009"
.AddItem"2010"
.AddItem"2011"
.AddItem"2012"
.AddItem"2013"
.AddItem"2014"
EndWith
'ResetRadioButton.SetittoFalsewhenformloads.
'ResetRadioButton.SetittoFalsewhenformloads.
radioyes.Value=False
radiono.Value=False
EndSub
Step8:NowweneedtoaddcodetotheSubmitbutton.UponClickingonsubmitbutton
userShouldbeabletoAddthevaluesintotheworksheet.
PrivateSubbtnsubmit_Click()
DimemptyRowAsLong
'MakeSheet1active
Sheet1.Activate
'DetermineemptyRow
emptyRow=WorksheetFunction.CountA(Range("A:A"))+1
'Transferinformation
Cells(emptyRow,1).Value=txtempid.Value
Cells(emptyRow,2).Value=txtfirstname.Value
Cells(emptyRow,3).Value=txtlastname.Value
Cells(emptyRow,4).Value=cmbdate.Value&"/"&cmbmonth.Value&"/"&cmbyear.Value
Cells(emptyRow,5).Value=txtemailid.Value
Ifradioyes.Value=TrueThen
Cells(emptyRow,6).Value="Yes"
Else
Cells(emptyRow,6).Value="No"
EndIf
EndSub
Step9:Nowaddamethodtoclosetheformwhenuserclicksoncancelbutton.
PrivateSubbtncancel_Click()
UnloadMe
EndSub
Step10:NowLetusExecutetheFormbyclickingon"run"Button.Entervaluesintothe
form and click 'Submit' button. Automatically the values would flow into the worksheet as
shownbelow.
PreviousPage
NextPage
Advertisements
Write for us
FAQ's
Helping
Contact
go