Вы находитесь на странице: 1из 3

ExcelVBAReferenceGuide

BacktoExcelHomepage

EventHandling

VBAHOMEPAGE
Menu

AnEventissomethingthathappensinaprogramsuchas:

Recordingmacros
Lookingatthecode

Openingorclosingaworkbook

Waysofrunningmacros

Savingaworkbook

Wheremacrosarestored

Activatingordeactivatingaworksheetorwindow

Reasonstowritemacros

Pressingakeyorkeycombinations

Writingmacros

Entering/Editingdataintheworksheet

Proceduretypes
VisualBasiceditor(VBE)

Clickingthemouseonacontrol/object

Rules&conventions

Doubleclickingonacell

Excelobjects

Datainachartisupdated

Range/Selectionobjects

Recalculatingtheworksheet

Objecthierarchy

Aparticulartimeofdayoccurs

Objectbrowser
Chartobjects

YoucanthereforerunaprocedureautomaticallywhenacertainEventinExceloccurs.

PivotTableobjects

Formulas

Therearedifferentobjects(andthereforedifferentlevels)whenExcelautomaticallytriggers
aprocedureasthesystemisconstantlylisteningfortheeventtooccur.

VisualBasicFunctions
CreatingAddIns
Variables&constants

WorkbookEvents

Objectvariables
Arrays

OpenEvent

Collections

ThemostcommontypeofOpenEventisWorkbook_Open.Thisprocedureisexecuted
whentheworkbookisopenedandisoftenusedforthetaskssuchas:

MessageBox
VBAInputBox
ExcelInputBox
Makingdecisions(If)

Displayingawelcomemessage
Openingotherworkbooks

Makingdecisions(Case)

Settingupcustommenusandtoolbars

Looping(Do...Loop)

Activatingaparticularsheetorcell

Looping(For...Loop)
With...EndWithblocks

Example:

Eventhandling

Everytimetheuseropenstheworkbook,theyaregreetedwithamessageboxdisplaying
thedayoftheweek.IfitisaFriday,amessageboxwillremindtheusertosubmittheir
timesheet.

Errorhandling

1.Opentherequiredworkbook.

Debugging

2.SwitchtotheVisualBasicEditor.

CreatingUserForms

3.DoubleclickonThisWorkbookfromwithintheProjectExplorer.

Userdefinedfunctions

DAO/ADOObjects
Input/OutputFiles

Otherlinks

Examplecodesnippets
Userforminputexample

VBAKeyword:InuptBox,
MsgBox,Range,WeekdayName,
Weekday,Now,Date,
ActiveWindow,WindowState,
EntireColumn,AutoFit,Font&
Bold.

4.ClickontheObjectdropdownlistandselectWorkbook
5.EnterthefollowingbetweenthesignaturePrivateSubWorkbook_Open()
andEndSubkeywords:
PrivateSubWorkbook_Open()
MsgBox"Todayis"&WeekdayName(Weekday(Now),False,vbSunday)
IfWeekday(Now)=vbFridayThen
MsgBox"Don'tforgettosubmityourtimesheet"
EndIf
EndSub
Note:PrivatemeansthattheprocedurewontappearintheRunProceduredialogbox(i.e.Macros
dialog).SeeScope&VisibilityinVariables&Constantsforinformation.

WorkbookActivateEvent
Theprocedureisexecutedwhenevertheworkbookisactivated(getsthefocus).

Example:
CallthesignaturePrivateSubWorkbook_Activate()usingthesamemethodsas
previouslyexplainedabove.

Enterthefollowingcode:
PrivateSubWorkbook_Activate()
ActiveWindow.WindowState=xlMaximized
EndSub
Nowthewindowwillalwaysmaximisewhentheworkbookgetsthefocus.

Note:Deletinganevent(thesignature)willnotharmthesystemasitisregeneratedeachtimeyou
calloneofthepredefinedsignatures.

Example:
UsingthePrivateSubWorkbook_SheetActivate(ByValShAsObject)signature
istriggeredacrossanyworksheetintheactiveworkbook.

Enterthefollowingcode:
PrivateSubWorkbook_SheetActivate(ByValShAsObject)
Range("A1").Value=Date'EntersthecurrentdateinA1
Range("A2").Select'PositionthecursorinA2
EndSub
The'Sh'argumentcanalsobeusedtorefertowhichworksheetisbeingcalledshouldyou
wishtocontroltheindexornameofaparticularworksheetorgroupofworksheets.
Byincludingacodeline:IfSh.Name=Sheet3Then...itwillhandlethelogic

andcontrolflowfor'Sheet3'.
WorksheetEvents
WorksheetActivateEvent

Withinaworkbookyoualsohaveseparatenodesforeachaddedworksheetchartsheet
whichcontainaprivate(local)moduleoveranabovestandardmodulesinaVBAproject.

Example:
Everytimetheuserclickson'Sheet1'ifthefirstcell(A1)isemptythenprompttheuser
withanInputBoxfunctiontoenteratitle.
PrivateSubWorksheet_Activate()
IfTrim(Range("A1").value)=EmptyThen
Range("A1").Value=Trim(InputBox("Entertitle:"))
Range("A1").EntireColumn.AutoFit
EndIf
EndSub

Note:Ifthereareeventsatboththeworksheetandworkbooklevelwhichpointtothe
sameobject(worksheet),thenit'stheworksheetlevelwillrunfirstfollowedbythe
workbookevent.

OtherEvents
ThereareotherwaystogetExceltotriggeramacrousingothereventsfromotherobjects
orcontrols.
ItispossibletoattachprocedurestotheActiveXControlssothatwhenevertheuserclicks
ontoacontrol,theprocedurewillrun.

Example:
WhentheuserclicksontheCommandButton,amessageboxwillappear.

1.FromExcel,clickontheDevelopertab(RibbonBar),selectInserticon
andchooseButtoniconfromtheFormControlsection.
2.DrawtheCommandButtonontothespreadsheet.
3.TheAssignMacrodialogboxappears,ClicktheNew...button.
4.Enterthefollowingcode:
SubButton37_Click()
MsgBox"Buttonclickevent!"
EndSub

Anycontroldrawnonaworksheetoruserformwillhavepredefinedeventsthatcanbe
codedtorespondbythesystem.

Howdoyouthinkfeatureslikeconditionalformattinganddatavalidationworkina
worksheetwhensetinExcel?Whentheuserentersavalueinacell,theChangeeventis
triggered:
PrivateSubWorksheet_Change(ByValTargetAsRange)
IfTarget=Range("A2")ThenRange("A2").Font.Bold=True
EndSub
Targetistheargumenttotestwhichcelladdressisbeingchanged.

NextTopic:ErrorHandling

WanttoteachyourselfAccess?FreeonlineguideatAboutAccessDatabases

Home|TermsofUse|PrivacyPolicy|Contact
copyright2010TPDevelopment&ConsultancyLtd,AllRightsReserved.
Alltrademarksarecopyrightedbytheirrespectiveowners.Pleasereadourtermsofuseandprivacypolicy.