Vous êtes sur la page 1sur 18

14/3/2017 VBAforBeginners:VBAUserformsOnlinePCLearning

OnlinePCLearning
(http://www.onlinepclearning.com)

VBA for Beginners: VBA


Userforms

(http://www.onlinepclearning.com/vbabeginnersvbauserforms/)

BuildyourFirstUserformDatabase
Contents[show]

OVERVIEW
WhatisaUserform?
WhyuseaUserform?
UserformProject
InsertaUserform
UserformProperties
Toolbox
AddingControls
Writingourcode

WhatisaUserform?
AuserformisadialogboxthatyoucreateandcustomizeintheVisualBasic
Editor.ItisanobjectthatcancontainVBAcodeandevents.Youcanadda
largevarietyofcontrolstotheuserform.


http://www.onlinepclearning.com/vbabeginnersvbauserforms/ Opentheresourcefile 1/18
14/3/2017 VBAforBeginners:VBAUserformsOnlinePCLearning

Opentheresourcefile
OpentheresourcefilethatcamewiththiseBook
andnavigatetotheUserformworksheet.Thiswill
enableyoutotesteachoftheseexamples.

Hereistheformthatwewillbeusingtocollectand
addourreceipts.

WhyuseaUserform?
Auserformpresentsauserfriendlyinterface.Fromthisplatformyoucan
controltheoptionsavailabletotheenduser.Youdonothavetogotothe
worksheet.Itisoftengoodtopreventthis.

Userformsenableavarietyofpossibleusesthatotherwisewouldbedifficult
toachieveatasheetlevel.

CommonUserformUses
Dataentrycontrol
Selectingranges
Splashscreens
Filteredworksheetdata
Addmultiplepagestotheuserform
Menuforyourapplication
PopupCalendars
Navigationforallsheets

InharmonywiththespiritofOnlinePCLearning
(http://www.onlinepclearning.com/)wewillbelearninghowtouseuserforms
bydevelopingaproject.

UserformProject
OurprojectisMyTaxReceipts.Itwillenableyoutoaddandsortyourtax
receiptsforyearsintoadatabasewithoutleavingtheuserform.Youcanthen
filterthetaxreceiptsbetweendatesfromaninterfacesheet.Thisisagreat

http://www.onlinepclearning.com/vbabeginnersvbauserforms/ 2/18
14/3/2017 VBAforBeginners:VBAUserformsOnlinePCLearning

littleprojecttogetstartedwithlearningtouseuserformsinVBA.

Theillustrationbelowshowstheinterfacesheetandtheuserformreadyfor
action.

(http://www.onlinepclearning.com/wpcontent/uploads/2013/11/userform
project.png)

Addingthreedynamicnamedranges
Beforewegetstartedweneedtoaddthreedynamicnamedrangestothe
workbook.

ChangethenameofSheet3inyourworkbooktoListsandincellsD4/H4/F4
addtheheadersthatyouseebelow.

1.TaxCategory2.StoredLocation3.Company

Note:Makesurethatthereisdataundertheheadersasournamed
rangesaregoingtobedynamic.IfthereisnodataforVBAtofind,an
errorwilloccur.Copytheinformationfromtheillustration.

(http://www.onlinepclearning.com/wpcontent/uploads/2013/11/userform
lists.png)

Thesethreedynamicnamedrangeswillbethevaluesthatpopulateour
threecomboboxessowewilladdthematthebeginningofthisproject.From
theribbononyourExcelspreadsheetchooseFormulas/Name
Manager/Newthenaddthenamebelowandtheformulatocreatethree
dynamicnamedranges.Category/Company/Location

Category=OFFSET(Lists!$D$5,,,COUNTA(Lists!$D$5:$D$100))

Company=OFFSET(Lists!$H$5,,,COUNTA(Lists!$H$5:$H$100))

Location=OFFSET(Lists!$F$5,,,COUNTA(Lists!$F$5:$F$100))

http://www.onlinepclearning.com/vbabeginnersvbauserforms/ 3/18
14/3/2017 VBAforBeginners:VBAUserformsOnlinePCLearning

Hereisthelinktothewebsitearticleforunderstandingdynamicnamed
ranges

Note:Youcanuseastaticnamedrangehoweveryouwouldneedto
redefineiteachtimenewdataisadded.

ExcelDynamicNamedRanges:AddPowerandPunchtoExcel(/excel
dynamicnamedranges/)

Note:Youcanuseastaticnamedrangehoweveryouwouldneedto
redefineiteachtimenewdataisadded.

VisualBasicEditor
PreviouslyIhavediscussedthevisualbasiceditorinChapter2.Ifyouhave
notreadthatchapterortheinformationisalittlehazythenpleaserevisitthis
article.

UnderstandingtheVBAEditor(/vbaforbeginnersunderstandingvba/)

InsertaUserform
Howtocreateauserform!

OpenMicrosoftExcelandusetheshortcutkeyAlt+F11toopentheVisual
BasicEditor.

1.ClicktheInsertTab
2.ChooseUserform
3.Theuserformwillappear.Thewhiteboxesonthesideoftheuserform
willenableyoutoresizetheformtoyourapproximateneeds.
4.VBAwillhidethetoolboxifitthinksyouarenotusingit.Clickinside
theuserformanditshouldappear.Ifitisnotvisiblethenchoosethe
ViewtabandclickToolbox.
5.FromtheViewtabclickPropertiesifitisnotvisible

WewillneedtohavequickaccesstotheToolboxandthePropertiesdialog
box.

UserformProperties
Whenyouclickinsidetheuserformyoushouldseeadottedborderaroundit.
Whenthisoccursthepropertiesdialogboxwilldisplaytheuserform
properties.


http://www.onlinepclearning.com/vbabeginnersvbauserforms/ 4/18
14/3/2017 VBAforBeginners:VBAUserformsOnlinePCLearning

ForourprojectwewanttochangethenameoftheuserformfromUserform1
toanamethatwillhelpustounderstandtheuserformanditspurpose.Todo
thiswewilluseabasicnamingconvention.WhenworkinginVBAyoushould
useanamingconventionthatisconsistent.

InthepropertiesboxnametheuserformfrmTax_Receipt(nospaces
allowed)andaddacaptionMyTaxReceipts(spacesareallowedhere)

Hereisasampleofthenamingconventionthatiscommonlyused.

Userformsstartwithfrm
Textboxesstartwithtxt
Comboboxesstartwithcbo
Labelsstartwithlbl(ifyouarenotreferringtothelabelsinyoucode
thereisnoneedtogivethemaspecialname)

TheonlyrulesthatapplyarenottouseareservedVBAkeywordnoradd
spacesinthename.

Note:Atthisstageoftheprojectyouruserformshouldnowhaveanameand
acaption.IfyouwanttoseewhattheuserformwilllooklikeinExcelthen
pushtheF5keyorclicktheRunbuttoninthemenuatthetop.Toreturntothe
VBE,closetheuserformbyclickingthexinthetoprighthandcornerofthe
userform.

Notethedottedborderwhentheuserformisselectedandthenewnamefor
theuserformintheProjectExplorer.

Toolbox
TheToolboxcontainsallofourcontrolsthatcanbeaddedtotheuserform.
Placethecurseroverthecontrolstorevealthenameofthecontrol.Ifyou
needtousecontrolsthatarenotinthetoolboxthenrightclickinsideofthe
toolboxandchooseAdditionControls.TheAdditionalcontrolsdialogbox
willappear.Asyouscrolldownyouwillseesomecontrolshavean(x)inthe
boxonthelefthandside.Thesearetheavailablecontrolsinthetoolbox.To
addadditionalcontrolsaddan(x)intheboxandclickOK.Toremovea
control,clickinsidethesquaretoremovethexandthenclickOK.

Note:NotallofthesecontrolsareavailabletoVBAExcel.


http://www.onlinepclearning.com/vbabeginnersvbauserforms/ 5/18
14/3/2017 VBAforBeginners:VBAUserformsOnlinePCLearning

AddingControls
AddingLabels
Wehave12labelstoaddtotheuserform.

ToaddalabelclickonthelabelintheToolboxandthenreturntoyour
Userformandclickdownontheleftmousebuttonanddragthelabeloverthe
formuntilthecontrolisthedesiredsize.

HereareninelabelsthatyouwillneedtoaddtotheUserformfornow.You
willnoticethatspacesareallowedbetweenthewordsinthelabelsandthat
youareabletochangethefontsizeandcolourandstyletosuityourtaste.

(http://www.onlinepclearning.com/wp
content/uploads/2013/11/Userformlabels.png)

Nowthatyouhaveyourlabel,rightclickandchooseProperties.Youwillbe
abletochangethelabelnamebutmostimportantlywewanttochangethe
Caption.Whilethepropertiesboxisopensetthesizeofthefontthatyou
wantandthefonttypeandstyle.

Note:Inthepropertiesboxyouareabletoselectthewaythattheproperties
foranycontrolinouruserformareformattedandbehave.Youhavethe
choiceofAlphabeticorCategorizedtabsatthetopofthePropertiesdialog
boxtochoosefrom.

TopTip:Onceyouhaveformattedonelabelrightclickandcopyiteleven
timesontotheform.AlignthelabelstosuitandchangetheCaptionsto
reflecttheninelabelsthatyouseeintheillustrationabove.Thelabelswillnot
bereferencedintheVBAproject.
http://www.onlinepclearning.com/vbabeginnersvbauserforms/ 6/18
14/3/2017 VBAforBeginners:VBAUserformsOnlinePCLearning

Aswellistheninetextlabelswehavethreelabelsthatwillindicatethefields
thatwillbemandatory.Theselabelssimplyhaveanasteriskinsideofthem
thatisformattedtoalargerfontsizeandcoloredred.Createoneandcopy
theothertwoandmovethemtothecorrectplaceontheuserform,asshown
intheillustrationbelow.

Listforcontrolnames
Asyoucanseefromtheillustrationbelowwehave:

12labels
4textboxes
3comboboxes
2optionbuttonsthataregrouped
3commandbuttons
1imageframe


Thisgivesusatotalof25controlsontheUserform.Makesurethatthetext
boxes,comboboxes,optionbuttonsandcommandbuttonshaveexactlythe
samenamesasyouseebelowortheVBAcodethatyouwillbeaddingwill
notwork.


http://www.onlinepclearning.com/vbabeginnersvbauserforms/ 7/18
14/3/2017 VBAforBeginners:VBAUserformsOnlinePCLearning

(http://www.onlinepclearning.com/wp
content/uploads/2013/11/userformcomplete.png)

AddingTextBoxControls
Toaddatextbox,clickonthetextboxiconintheToolboxandthenreturnto
yourUserformandclickdownontheleftmousebuttonanddragthetextbox
overtheform.

Theonlythingthatweneedtodotoourtextboxcontrolsistoaddthecorrect
nametothem.

Note:
Copythecontrolnamesfromtheillustrationabove.

AddingComboboxcontrols
Addthecomboboxcontrolstotheuserforminthesamemannerasthetext
boxesandlabels.Makesurethatthenameiscorrectforeachofthethree
comboboxcontrols.Asyoucanseefromtheillustrationbelowwearegoing
topopulateeachcomboboxwithadynamicnamedrangethatyou
previouslyaddedintothenamemanager.

Theillustrationbelowshowswherethedynamicnamedrangeshouldbe
typedintheRowSourceofthepropertiesofthecombobox.

Makesurethattherangeshavedatainthem.VBAwouldbelookingfora
namedrangethatasyetdoesnotexistiftherangesareempty.


http://www.onlinepclearning.com/vbabeginnersvbauserforms/ 8/18
14/3/2017 VBAforBeginners:VBAUserformsOnlinePCLearning

Youcansettheoptiontoallowausertoadddifferentvaluesfromthoseinthe
rangetoacomboboxifyouwish.InthepropertiesselectMatchEntryand
choose2MatchEntryNone(illustrationbelow).Ifyouallowthisthen
analyzingthedataatalaterdatecanbealittledifficult.

(http://www.onlinepclearning.com/wp
content/uploads/2013/11/userformmatchentry.png)

OptionButtons
Aswellasassigningthecorrectnamestoouroptionbuttonsweneedto
groupthe2buttonstogether.Toaccomplishthisselectbothbuttonsby
draggingthecurseroverbothofthemorbyholdingdowntheshiftkeyand
clickingonthebothoptionbuttons.Rightclickonthetwoselectedbuttons
andfromthedropdownmenuchooseGroup.

OptionButtons
Aswellasassigningthecorrectnamestoouroptionbuttonsweneedto
groupthetwobuttonstogether.Toaccomplishthisselectbothbuttonsby
draggingthecurseroverbothofthemorbyholdingdowntheshiftkeyand
clickingonthebothoptionbuttons.Rightclickonthetwoselectedbuttons
andfromthedropdownmenuchooseGroup.

AddingaPicture
Ifyouwishtoaddapictureoralogotoyouruserformthenfollowthesetwo
steps.

1.Firstpreparethepictureorlogoandmakesurethatitisaverysmall
image.TheimagethatIusedinthisUserformisa7kB.Iwillbriefly
describehowIformattedthisimage.Thisimagewasformattedby
openingaMicrosoftPowerPointandinsertingclipartoryourimage
(logo)thatyoufeelwouldbeappropriatetothethemeofthis
application.ThebackgroundwasthenremovedinPowerPointand
theimagewassavedtoalocationonthedesktopbyrightclickingand
choosingSaveImageAs.Onthedesktoptheimagewasrightclicked
andopenedinMicrosoftPictureManagerwhereitwasresizedto7
kb.

2.Secondaddanimagecontroltotheuserform.Asyoucanseefromthe
illustrationbelowwecanaddthepicturebyclickingPictureandthenlocating
ourimagetoimportitintothecontrol.Notethetwopropertiesbelow:

a.PictureAlignment

http://www.onlinepclearning.com/vbabeginnersvbauserforms/ 9/18
14/3/2017 VBAforBeginners:VBAUserformsOnlinePCLearning

b.PictureSizeMode.

Thesepropertieswillallowyoutomanipulatetheimagewithinthecontrol.

(http://www.onlinepclearning.com/wp
content/uploads/2013/11/userformimage.png)

Taborder
Tosetthetaborderforthecontrolsinyouruserform,clickontheViewTab
andchooseTabOrder(illustrationbelow).Movethecontrolsupanddownto
suittheorderthatyouwouldliketheTabkeytomovethroughthem.

WritingtheVBACode
Thefirstthingthatwewanttodoistorunasmallpieceofcodetoopenthe
Userformfromabuttonontheworksheet.

FromtheInserttabintheVBEchooseModule.Intothenewlycreated
moduleaddthissmallpieceofVBAcode.

SubShowme()
frmTax_Receipts.Show
EndSub


http://www.onlinepclearning.com/vbabeginnersvbauserforms/ 10/18
14/3/2017 VBAforBeginners:VBAUserformsOnlinePCLearning

NamethethreeworksheetsInterface,DatabaseandLists.OntheInterface
sheetinsertarectangleshapethenrightclickontheshapeandchoose
AssignMacro.SelectthemacroShowmeandclickOK.

Testtheuserform
ClickonthebuttonandtheUserformshouldappearabovetheworksheet.Do
notmoveforwardwiththerestofthisprojectuntilthisissuccessfullyworking.
Checkthatthethreecomboboxeshavethevaluescontainedinthethree
dynamicnamedranges.

Addingourcode
IntheVBEdoubleclickontheuserformintheProjectexplorer.Nowdouble
clickonthecmdAddbutton.

TheclickeventprocedurebelowwillappearintheVBE.

PrivateSubcmdAdd_Click()

(VBAcodegoeshere)

EndSub

OurVBAcodewhichwilltaketheinformationfromtheuserformandadditto
thedatabaselistwillappearbetweenthesetwolines.

Sixthingsthatthisprocedurewillaccomplish:
1.Declareourvariables
2.Add2variables
3.Add2Ifstatementstocheckthatadateisaddedandthatour
mandatoryfieldshavebeenfilledin.
4.MovetheinformationfromtheUserformtothedatabase.
5.Sortofthedatabase
6.ResettheUserform

Declareourvariables
ThiscodeisdimensioningourvariableswhichsimplymeanstellingVBAthe
datatypeforeachvariable.

DimwsAsWorksheet

DimaddmeAsRange

Addthevariables
Thesetwovariablesarefortheworksheetthatcontainsthedatabaseandfor
thenextemptyrowinourdatabaselist.

Setws=Sheet2

Setaddme=ws.Cells(Rows.Count,4).End(xlUp).Offset(1,0)

AddtwoIfstatementstocheckthatadateisadded
andthatourmandatoryfieldshavebeenfilledin.
AcommonmistakethatmanymakewithUserformsistoaddadate
incorrectly.Wearegoingtocheckthedateisinfactadatebeforeweallow
theusertoproceed.



http://www.onlinepclearning.com/vbabeginnersvbauserforms/ 11/18
14/3/2017 VBAforBeginners:VBAUserformsOnlinePCLearning

IfNotIsDate(txtDate.Value)Then

MsgBox"Thedatefieldmustbeaproperdate",vbExclamation,
"Dateformaterror"

Me.txtDate.Value=""

Me.txtDate.SetFocus

ExitSub

EndIf

OurUserformhasthreemandatorilyfieldsthatneedtobecheckedtoseeifa
valueexistsineachbeforewecanprocesstheuserform.TheIfstatement
belowchecksofthesethreefields.

IfMe.txtDate.Value=""OrMe.cboCompany.Value=""Or
Me.txtAmount.Value=""Then

MsgBox"Thereisinsufficientdata.Madatoryfieldsmustbeadded
(*)",vbExclamation,"Mandatoryfieldsareincomplete"

ExitSub

EndIf

MovetheinformationfromtheUserformtothe
database.
Wereferenceourvariableaddmetofindthenextavailablecelltoaddour
firstvaluefromtheuserform.WhenwefindthatcellweaddourtxtDateand
thenoffsetonecolumninthesamerowandaddourcboCompanythen
offsetonecolumnandaddtxtDescriptionthenoffsetonecolumnandadd
ourcboCategoryetcetera.WhenwegettoouroptionbuttonwerunanIf
/ElseIf/Elsestatementtocheckandtosendtherightvaluetoourdatabase.

NoticethatweformatthetxtDate.Youwillneedtochangethisdependingon
thelocationinwhichyouliveintheworld.AndwealsoformatourtxtAmount
ascurrency.

Withws

'setthedateformattosuityourarea

addme.Value=Format(txtDate.Value,"mm/dd/yy")

addme.Offset(0,1).Value=Me.cboCompany.Value

addme.Offset(0,2).Value=Me.txtDescription

addme.Offset(0,3).Value=Me.cboCategory

addme.Offset(0,4).Value=Format(Me.txtAmount.Value,
"$##,###.00")

IfOPT1.Value=TrueThen

addme.Offset(0,5).Value="PaperCopy"

http://www.onlinepclearning.com/vbabeginnersvbauserforms/ 12/18
14/3/2017 VBAforBeginners:VBAUserformsOnlinePCLearning

ElseIfOPT2.Value=TrueThen

addme.Offset(0,5).Value="ScannedCopy"

Else

addme.Offset(0,5).Value=""

EndIf

addme.Offset(0,6).Value=cboLocation

addme.Offset(0,7).Value=txtRemarks

EndWith

Sortingthedatabase
Livingintherealworldweknowthatourdatesarenotalwaysgoingtobe
addedinconsecutivedateorder.Sotodealwiththisproblemwearegoingto
sortthedataeachtimeweaddanewtaxreceipt.Thedataissortedbydates
andinascendingorder.

ws.Select

Withws

ws.Range("D4:K10000").SortKey1:=Range("D4"),
Order1:=xlAscending,Header:=xlGuess

EndWith

'returntosheet

Sheet1.Select

ResettheUserform
TherearethreewaystoresettheUserform.

1.Addeachcontrolnameandassignblankasthevalue
Me.txtDate.value=
2.ReferenceeachcontroltypeintheUserformandassignblankasthe
value
ForEachctlInMe.Controls
IfTypeName(ctl)="TextBox"Thenctl.Value=""
Nextctl
3.ClosetheUserformandreopenit
UnloadMe
frmTax_Receipts.Show

Wearegoingtochoosethefinaloptionbecauseitistheeasiest.

BelowisthecompletecmdAddprocedure
Rememberthiscodegoesintotheuserformnotthemodule.Doubleclickon
thecmdAddbuttontoaccessthecodefortheuserform.Takethetimetolook
throughthecodeagainandmakesurethatyouunderstandexactlywhat
eachpartofthecodeisdoing.

PrivateSubcmdAdd_Click()
http://www.onlinepclearning.com/vbabeginnersvbauserforms/ 13/18
14/3/2017 VBAforBeginners:VBAUserformsOnlinePCLearning

'dimentionthevariable

DimwsAsWorksheet

DimaddmeAsRange

'setthevariable

Setws=Sheet2

'setvariableforthedestination

Setaddme=ws.Cells(Rows.Count,4).End(xlUp).Offset(1,0)

'holdinmemory

Application.ScreenUpdating=False

IfNotIsDate(txtDate.Value)Then

MsgBox"Thedatefieldmustbeaproperdate",vbExclamation,
"Dateformaterror"

Me.txtDate.Value=""

Me.txtDate.SetFocus

ExitSub

EndIf

IfMe.txtDate.Value=""OrMe.cboCompany.Value=""Or
Me.txtAmount.Value=""Then

MsgBox"Thereisinsufficientdata.Madatoryfieldsmustbeadded
(*)",vbExclamation,"Mandatoryfieldsareincomplete"

ExitSub

EndIf

'sendthevaluestothedatabase

Withws

'setthedateformattosuityourarea

addme.Value=Format(txtDate.Value,"mm/dd/yy")

addme.Offset(0,1).Value=Me.cboCompany.Value

addme.Offset(0,2).Value=Me.txtDescription

addme.Offset(0,3).Value=Me.cboCategory

addme.Offset(0,4).Value=Format(Me.txtAmount.Value,
"$##,###.00")

IfOPT1.Value=TrueThen

addme.Offset(0,5).Value="PaperCopy"

ElseIfOPT2.Value=TrueThen

addme.Offset(0,5).Value="ScannedCopy"

Else
http://www.onlinepclearning.com/vbabeginnersvbauserforms/ 14/18
14/3/2017 VBAforBeginners:VBAUserformsOnlinePCLearning

addme.Offset(0,5).Value=""

EndIf

addme.Offset(0,6).Value=cboLocation

addme.Offset(0,7).Value=txtRemarks

EndWith

'sortthedata

Sheet2.Select

Withws

ws.Range("D4:K10000").SortKey1:=Range("D4"),
Order1:=xlAscending,Header:=xlGuess

EndWith

'returntosheet

Sheet1.Select

'resettheform

UnloadMe

frmTax_Receipts.Show

'updatethesheet

Application.ScreenUpdating=True

EndSub

ClosetheUserform
DoubleclickonthecmdClosebuttonandaddtheVBAcodebetweenthe
twolines.

UnloadMe

PrivateSubcmdClose_Click()

UnloadMe

EndSub

ResettheUserform
PrivateSubcmdReset_Click()

UnloadMe

frmTax_Receipts.Show

EndSub

SetuptheDatabase
Onthedatabasesheetaddtheseheaderstothecellreferencesshown
below.(Refertoillustrationbelow)

CellD4ReceiptDate
http://www.onlinepclearning.com/vbabeginnersvbauserforms/ 15/18
14/3/2017 VBAforBeginners:VBAUserformsOnlinePCLearning

CellE4Company

CellF4Description

CellG4TaxCategory

CellH4Amount

CellI4Type

CellJ4Location

CellK4Remarks

(http://www.onlinepclearning.com/wpcontent/uploads/2013/11/userform
database.png)

Testtheuserformwithdata
Returntotheinterfacesheetandclickonthebuttonthatyouaddedto
previouslytoopenyourUserform.Youwillnowbeabletoaddvaluestoyour
UserformandwhenyouclicktheAddbuttonthosevaluesshouldbemoved
tothedatabase.Testallthefunctionalitywithinthecodeandmakesurethat
themandatoryfieldswork.Testtheformanddataentrythoroughly.

WellthatsitforourUserformpartoftheproject.

Iamnowgoingtoshowyouhowyoucanfilterthatdatabasetobeableto
seeallofthetaxreceiptsbetweenanytwogivendates.Thiswillgiveour
programmorefunctionality.WecoulduseanotherUserformtodothisbutfor
nowwewillrunthisatasheetlevel.

SettingupTheInterface
Filteredresults(CopyTorange)
Ontheinterfacesheetaddexactlythesameheadersthatyouaddedtothe
databasesheetbutthistimestartatcellreferenceC7.

Note:Theseheadersmusthaveexactlythesamewordsthatyouusedinthe
database.Itisbesttocopyandpastethemtoensureaccuracy.

Thisiswhereyourfiltereddatawillbecopiedto.Itisnotnecessarytovisitthe
database.

(http://www.onlinepclearning.com/wpcontent/uploads/2013/11/userform
interface.png)

Startandfinishdates
http://www.onlinepclearning.com/vbabeginnersvbauserforms/ 16/18
14/3/2017 VBAforBeginners:VBAUserformsOnlinePCLearning

Directlyabovetheseheadersaddthesevaluesandformatstothecells
shownbelow.Thisiswhereyouwillenteryourstartingandfinishingdates.

CellC5StartDate

CellD5FinishDate

CellC6Formatthiscellasadatetype

CellD6Formatthiscellasadatetype

Advancedfiltercriteriablock
Totherightoftheseheadersaddthevaluesbelowtothecellreferencesand
thenthetwoformulastothecellreferencesindicated.Thetextmustbeexact
asthiswillformourcriteriablockfortheadvancedfilter.

CellM5ReceiptDate

CellN5ReceiptDate

CellM6=IF(C6="","",">"&C6)

CellN6=IF(D6="","","<"&D6)

Thesetwoformulaswillpickupyourstartandfinishdateandaddgreater
than(>)oraless(<)thansigntoeachdate.Inadditionifthedatesareblank
thecellswillbeblank.

Runningtheadvancedfilter
ReturntotheVisualBasiceditoranddoubleclickonthemoduleinthe
ProjectExplorerandinserttheVBAcodethatyouseebelow.

SubFilterme()

Sheet2.Range("D4").CurrentRegion.AdvancedFilter
Action:=xlFilterCopy,_

CriteriaRange:=Range("M5:N6"),CopyToRange:=Range("C7:J7"),
Unique:=False

EndSub

Gobacktotheinterfacesheetandinsertashape,rightclickontheshape
andchooseAssignMacroandselectthemacroFilterMe.

Afteryouhaveaddedmultiplevaluestothedatabase,runsometestswiththe
advancedfilterbyaddingstartandfinishingdates.

InConclusion
http://www.onlinepclearning.com/vbabeginnersvbauserforms/ 17/18
14/3/2017 VBAforBeginners:VBAUserformsOnlinePCLearning

InthisprojectwehavelearnedmanythingsabouthowaUserformworksand
howwecanuseittospeedupourdataentryprocess.Thisisjustthetipof
theiceberg.YouwillfindthatyouwillbeusingUserformsallthetimeinorder
toenhancetheuserexperience,controldatamovementanddataentryin
yourapplications.

Related

(http://www.onlinepclearning.com/multi
(http://www.onlinepclearning.com/staff
(http://www.onlinepclearning.com/excel
pageuserform trainingmanager userformtoexport
employeedatabase/) exceldatabase/) andimportfrom
MultiPage StaffTraining access/)
Userform ManagerDatabase ExcelUserformto
Employee ExcelUserform ExportandImport
Database fromAccess
(http://www.onlinepclearning.com/staff
(http://www.onlinepclearning.com/multi
trainingmanager (http://www.onlinepclearning.com/excel
pageuserform exceldatabase/) userformtoexport
employee February4,2014 andimportfrom
database/) In"ExcelProjects access/)
August26,2015 UserformVBA April15,2015
In"ExcelProjects Training" In"ExcelProjects
UserformVBA UserformVBA
Training" Training"

2commentsonVBAforBeginners:VBA
Userforms

florenciadepelflorencia(http://gravatar.com/florenciadepel)
December11,2013at4:37pm(http://www.onlinepclearning.com/vba
beginnersvbauserforms/#comment531)

Setws=Sheets(2)

'error13,helpme

TrevorEaston(http://www.onlinepclearning.com)
December11,2013at4:44pm
(http://www.onlinepclearning.com/vbabeginnersvba
userforms/#comment532)
http://www.onlinepclearning.com/vbabeginnersvbauserforms/ 18/18