41
Automating Excel ® an Introduction to VBA Presented By: This manual was created for online viewing. State specific information in this manual is used for illustration and is an example only. MAIL: P.O. Box 509 Eau Claire, WI 54702-0509 • TELEPHONE: 866-352-9539 • FAX: 715-833-3953 EMAIL: [email protected]WEBSITE: www.lorman.com • SEMINAR ID: 400666 Mike Thomas theexceltrainer.co.uk

Final- Automating Excel - An Introduction to VBA

  • Upload
    others

  • View
    10

  • Download
    0

Embed Size (px)

Citation preview

Automating Excel® – an Introduction to VBA

Presented By:

This manual was created for online viewing. State specific information in this manual is used for illustration and is an example only.

mail: P.O. Box 509 Eau Claire, WI 54702-0509 • telephone: 866-352-9539 • fax: 715-833-3953email: [email protected] • website: www.lorman.com • seminar id: 400666

Mike Thomastheexceltrainer.co.uk

Take advantage of this special offer for $50 off of a Lorman

live webinar!

C O N V E N I E N T:Lorman offers a wide variety of live webinars covering current issues affecting numerous industries. Learn the latest on legal compliance, cost savings and strategies, and business trends.

E X P E R I E N C E D :Learn about today’s hot topics presented by our expert speakers who represent prominent firms and have years of industry experience and knowledge.

C U R R E N T :In today’s business world, staying current of the ever-changing regulations is absolutely necessary in order to advance in your field. Earn continuing education credits, educate your entire team and ask questions of the speakers. For a complete listing of upcoming live webinars visit www.lorman.com.

SPECIAL OFFER

$50 OFFYOUR NEXT Discount Code Y1719669This offer can not be used in combination with other discounts.

LIVE WEBINAR

Automating Excel® – an Introduction to VBA

©2017 Lorman Education Services. All Rights Reserved.

All Rights Reserved. Lorman programs are copyrighted and may not be recorded or transcribed in whole or part without its express prior written permission. Your attendance at a Lorman seminar constitutes your agreement not to record or transcribe all or any part of it.

Full terms and conditions available at www.lorman.com/terms.php.

This publication is designed to provide general information on the topic presented. It is sold with the understanding that the publisher is not engaged in rendering any legal or professional services. The opinions or viewpoints expressed by faculty members do not necessarily reflect those of Lorman Education Services. These materials were

prepared by the faculty who are solely responsible for the correctness and appropriateness of the content. Although this manual is prepared by professionals, the content and information provided should not be used as a substitute for professional services, and such content and information does not constitute legal or other professional

advice. If legal or other professional advice is required, the services of a professional should be sought. Lorman Education Services is in no way responsible or liable for any advice or information provided by the faculty.

This disclosure may be required by the Circular 230 regulations of the U.S. Treasury and the Internal Revenue Service. We inform you that any federal tax advice contained in this written communication (including any attachments) is not intended to be used, and cannot be used, for the purpose of (i) avoiding federal tax penalties imposed by

the federal government or (ii) promoting, marketing or recommending to another party any tax related matters addressed herein.

mail: P.O. Box 509 Eau Claire, WI 54702-0509 • telephone: 866-352-9539 • fax: 715-833-3953email: [email protected] • website: www.lorman.com • seminar id: 400666

Prepared By:Mike Thomas

theexceltrainer.co.uk

Learn What You Want, When You Want From Our Entire

Course Library

UNLIMITED ACCESS

ON-THE-GO LEARNING

We Offer Accredited Training Including CLE, CPE, HRCI, ENG and Many More

A L L - A C C E S S P A S SLORMAN EDUCATION SERVICES

Learn at Your Own Pace From Your Computer,

Tablet or Mobile Device

lorman.com/pass

GET CERTIFIED

Want to learn more? Contact a Lorman

All-Access Pass Specialist:

[email protected] or call 1-877-296-2169

Automating Excel: An Introduction to VBA

Mike Thomas

1

2

VBA (Visual Basic for Applications)

A computer programming language

3

Built into Excel, Word, PowerPointand other Microsoft apps

MacroMacro

4

Each month…Open my month-end consolidation fileLots of copying & pasting of dataDelete some rows and columnsFormat some data to display correctlySave the updated file

2 hours

Click a single buttonRun a macro 30 seconds

Macro Recorder

5

Mike Thomas

This training focuses on what you need to know in order to use the VBA toolset to automate basic tasks

6

10

Objects

Collections

Properties

Methods

Objects in ExcelObjectApplicationWorkbookWorksheetRangeRowColumn

7

Collections

iPhones(3)

iPhones("07990 123456")

Collections in Excel

Worksheets(6)

Worksheets("Sheet6")

8

Object Model (Excel)

Referencing an Object

Application.Workbooks("my-file.xls").Worksheets("Sheet2").Range("C29")

Range("C29")

9

Special Objects in Excel

Object

ActiveCell

ActiveWorkbook

ActiveRow

Properties (Characteristics)

Name ValueColour BlackManufacturer AppleCapacity 32GBFreeSpace 2GBIsFullyCharged False

10

Properties: Can be changed

Name Value

FreeSpace 2GB

IsFullyCharged False

Properties: Can’t Be Changed

Name Value

Colour Black

Manufacturer Apple

Capacity 32GB

11

Range Object: Properties

Name Value

Address A1

Value Here is some text

Name Demo

WrapText True

Methods (Actions)

MethodAnswerCallUnlockLockDisplayNextScreenSwitchOff

12

Range Object: Methods

Method

Select

ClearContents

Copy

Cut

Email: [email protected]

The Excel Trainer: http://theexceltrainer.co.uk

Mike Thomas

13

14

AutomatingExcel:

MacrosandVBAFundamentals

Trainer:MikeThomas

15

http://theexceltrainer.co.uk

WhatisVBA?• ItstandsforVisualBasicforApplications• It'saprogramminglanguage• It'sbuiltintoExcel,Word,Excel,PowerPointandseveralotherMSapplications.The

trainingfocussesonVBAinExcel

WhatisaMacro?• InExcel,amacroisasetofkeystrokesorcommandsstoredunderandname,whichcan

be"playedback"byissuingasingleinstruction,therebysavingyoutime.

TheMacroRecorderandVBA• Excelhasabuilt-inmacrorecorderthatletsyoucreateamacrobyactuallyrecordingthe

actions,however,themacrorecorderdoeshavelimitationssotobeabletodoanythingmorethanjustrecordaseriesofcommandsorkeypresses,youneedtolearnVBA.

• AnotherreasonforlearningVBAistobeabletoeditexistingmacros.Evenifthemacrowascreatedwiththemacrorecorder,theonlywaytoamenditistoeitherrecorditagainfromscratchandreplacetheexistingoneoruseVBAtoeditit.

XLSXvXLSM• XLSXfiles(i.e.normalExcelworkbookfiles)cannotstoreVBAcode.• YoumustsavethefileasaMacro-Enabledfile(withanXLSMfileextension)

HowtoDisplaytheDeveloperTab:Office2010/2013/2016• ClickFile>Options• ClickCustomizeRibbon• PutatickintheDevelopercheckboxintheright-handcolumn

HowtoDisplaytheDeveloperTab:Office2007• ClicktheOfficebuttonandselectOptions• Inthefirstsetofoptionstickthebox"showdevelopertabontheRibbon

4WaystoRunaMacro1. DeveloperTab>Macrosandselectthemacrotorun2. PressALT+F8(shortcuttotheabove)3. Assignakeyboardshortcuttothemacro4. Addabuttontothespreadsheetandattachthemacrotoit

16

http://theexceltrainer.co.uk

EventProcedures• Aneventprocedureiscodethatrunsautomaticallywhenaneventoccurs• Examplesofeventso Workbookopeningo Workbookbeingclosedo Workbookbeingsavedo Switchingfromoneworksheettoanothero Switchingfromonecelltoanother

TheVBAEditor• ALT+F11toswitchbetweenExcelandVBAEditororDeveloper>VisualBasic• ProjectExplorerandPropertiesWindowaredisplayedontheleft-handside• Iftheyarenotdisplayed,usetheViewmenutodisplaythem• UsetheRunButton(greentriangle)torunthecurrentprocedure(current=wherethe

cursoris)

Procedures• InVBA,macrosarecalledProcedures• Procedureisaprogrammingterm,macroisafriendlierend-userterm• AllproceduresstartwiththewordSUBfollowedbyapairofbrackets• AllproceduresendwithENDSUB

Modules• Amoduleisacontainerforprocedures• Thereisnolimittothenumberofproceduresthatcanbestoredinasinglemodule• Youcancreatemorethanonemoduleinafiletoaidorganisingprocedures

EventProcedures• Canbeworkbook-specificorworksheet-specific• Mustbestoredintheappropriate"sheet"moduleorinthe"ThisWorkbook"module

EditingaMacro• PressALT+F8(orDeveloper>Macros)• Selectthenameofthemacro• ClickEdit

StepThroughaProcedure• Usefulwhentroubleshooting• Debug>StepintofromthetoolbarorF8

17

http://theexceltrainer.co.uk

CreateaNewProcedure• Placecursorwherenewprocedureistobestored• TypeSUBfollowedbyaspacefollowedbythenameandpressEnter

Modules• NewModule:SelectInsert>Module• RenameaModule:ClickthemoduleandrenameviathePropertieswindow• DeleteaModule:RightclickthemoduleandselectRemove

Indenting• UsetheTABkeytoindent• UseShiftandTABtoremoveanindent

Comments• Typeanapostropheatthestartofthelinetoaddacomment/note

ToAddaButtontotheSpreadsheet• Developertab>Insert• ClickthefirsticonintheFormssection• Drawthebutton• Selectthemacrotoattachtothebutton• Rightclickthebuttontochangetext/location/macro

ProtectingtheCode• Tools>VBAProjectProperties>Protection

18

http://theexceltrainer.co.uk

SampleCode:SelectingCellsSelectasinglecellRange("A1").SelectSelectarangeofcellsRange("A1:B10).SelectSelectacellonebelowA1Range("A1").Offset(1,0).SelectSelectacellonetorightofcurrentcellActivecell.Offset(0,1).SelectSelectfromcurrentcelltolastnon-blankcellincolumn(inclusive)Range(Selection,Selection.End(xlDown)).SelectSelectthenextblankcellincurrentcolumnActiveCell.End(xlDown).SelectActiveCell.Offset(1,0).Select

SampleCode:SettingCellValueSetthevalueofthecurrentcellto"TheExcelTrainer"Activecell.value="TheExcelTrainer"SetthevalueoftheA1to"TheExcelTrainer"Range("A1").value="TheExcelTrainer"SetthevalueoftheA1to100Range("A1").value=100EnteraformulainA1Range("A1").Value="=A3+A4"

EnterCurrenttimeintocurrentcellActiveCell.Value="=Now()"EnternameofcurrentuserintoA1(Windowsusername)Range("A1").Value=Environ("USERNAME")

19

http://theexceltrainer.co.uk

Logic(IF)IfA1contains"MikeThomas"thenput"ExcelVBA"intoB1andgotoC1.IfA1doesnotcontain"MikeThomas"thenput"Excel"inB1andgotoD1IfRange("A1").Value="MikeThomas"ThenRange("B1").Value="ExcelVBA"Range("C1").SelectElseRange("B1").Value="Excel"Range("D1").SelectEndIfIfA1contains"MikeThomas"thenput"ExcelVBA"intoB1.IfA1doesnotcontain"MikeThomas"thencontinueprocessingthecodefollowingthe"EndIf"IfRange("A1").Value="MikeThomas"ThenRange("B1").Value="ExcelVBA"EndIfIfA1contains"MikeThomas"thenput"ExcelVBA"intoB1.IfA1doesnotcontain"MikeThomas"thenignorethislineofcodeIfRange("A1").Value="MikeThomas"ThenRange("B1").Value="ExcelVBA"SelectCase–analternativetoalengthyIFfunctionIfthevalue(content)ofA1isMikeThomas,setB1toMT.Ifthevalue(content)ofA1isJohnDoe,setB1toJD.Ifthevalue(content)ofA1isRobertDoe,setB1toRD.Ifthevalue(content)ofA1isanythingelse,setB1toUnknownSelectCaseRange("A1").ValueCase"MikeThomas"Range("B1").Value="MT"Case"JohnDoe"Range("B1").Value="JD"Case"RobertDoe"Range("B1").Value="RD"CaseElseRange("B1").Value="Unknown"EndSelect

20

http://theexceltrainer.co.uk

Looping:RepeatingtheProcessGotoB2.ForeachcellincolumnB,settheformattodd-mmmm-yyyy.StopwhenitgetstoablankcellRange("B2").SelectDoUntilActiveCell.Value=""ActiveCell.NumberFormat="dd-mmmm-yyyy"ActiveCell.Offset(1,0).SelectLoopGotoB2.ForeachcellincolumnB,settheformattodd-mmmm-yyyy.Asitmovesdownthecolumn,checkcolumnD.StopwhenthereisablankcellincolumnDonthatrowRange("B2").SelectDoUntilActiveCell.Offset(0,2).Value=""ActiveCell.NumberFormat="dd-mmmm-yyyy"ActiveCell.Offset(1,0).SelectLoop

VariablesCreate2variablestostore"string"(i.e.text)values.Thevalueofthevariablescomesfrom2cellsDimvOrientationAsStringDimvPaperSizeAsStringvOrientation=Range("M1").ValuevPaperSize=Range("M2").ValueUsingavariableasacountertotrackthenumberoftimesaprocessisperformedDimCntrasbyteDimCntr1asbyteCntr1=Range("A1").ValueForCntr=1ToCntr1'Codegoeshere'CodegoeshereNextCntr

21

http://theexceltrainer.co.uk

FunctionsFunctiontoconvertaCelsiusvaluetoFahrenheitFunctionCelFar(vCelsiusAsInteger)CelFar=vCelsius*(9/5)+32EndFunctionScenario:A1=20.ThisisaCelsiustemperature.Inanothercell,type=CelFar(A1)TheresultofthefunctionistheFahrenheitequivalentof20degreesCelsius

22

OrderDate Flavour ContainerSize Quantity Revenue Cost City

1/4/2016 Banana 500ML 13 39.00 26.00 New York City

1/4/2016 Toffee 500ML 17 68.00 34.00 New York City

1/4/2016 Banana 1L 11 60.50 44.00 New York City

1/4/2016 Mint Chocolate500ML 10 35.00 20.00 New York City

1/4/2016 Strawberry 1L 16 80.00 32.00 New York City

1/4/2016 Chocolate 1L 14 98.00 70.00 New York City

1/4/2016 Toffee 500ML 19 76.00 38.00 New York City

1/4/2016 Strawberry 1L 15 75.00 30.00 New York City

1/4/2016 Vanilla 500ML 15 37.50 15.00 New York City

1/4/2016 Pecan 1L 14 77.00 42.00 New York City

23

24

OrderDate Flavour ContainerSize Quantity Revenue Cost City

1/4/2016 Banana 1L 16 88.00 64.00 Philadelphia

1/4/2016 Chocolate 500ML 19 76.00 38.00 Philadelphia

1/4/2016 Strawberry 1L 20 100.00 40.00 Philadelphia

1/4/2016 Chocolate 1L 15 105.00 75.00 Philadelphia

1/4/2016 Chocolate 500ML 12 48.00 24.00 Philadelphia

25

26

OrderDate Flavour ContainerSize Quantity Revenue Cost City

1/4/2016 Strawberry 1L 18 90.00 36.00 San Francisco

1/4/2016 Chocolate 500ML 17 68.00 34.00 San Francisco

1/4/2016 Banana 1L 17 93.50 68.00 San Francisco

1/4/2016 Peach 1L 17 93.50 51.00 San Francisco

1/4/2016 Mint Chocolate1L 11 71.50 33.00 San Francisco

1/4/2016 Vanilla 500ML 10 25.00 10.00 San Francisco

1/4/2016 Toffee 500ML 13 52.00 26.00 San Francisco

1/5/2016 Mint Chocolate1L 11 71.50 33.00 San Francisco

1/5/2016 Banana 1L 20 110.00 80.00 San Francisco

1/5/2016 Banana 500ML 13 39.00 26.00 San Francisco

1/5/2016 Toffee 1L 11 82.50 33.00 San Francisco

1/5/2016 Peach 500ML 20 60.00 40.00 San Francisco

1/5/2016 Vanilla 500ML 12 30.00 12.00 San Francisco

1/5/2016 Mint Chocolate500ML 15 52.50 30.00 San Francisco

1/5/2016 Pecan 500ML 10 30.00 10.00 San Francisco

1/5/2016 Chocolate 1L 19 133.00 95.00 San Francisco

1/5/2016 Peach 1L 20 110.00 60.00 San Francisco

1/5/2016 Banana 500ML 10 30.00 20.00 San Francisco

1/6/2016 Strawberry 1L 14 70.00 28.00 San Francisco

1/6/2016 Pecan 500ML 13 39.00 13.00 San Francisco

27

28

T

North,Week 2,6247

North,Week 3,5764

North,Week 4,7060

South,Week 1,6275

South,Week 2,7921

South,Week 3,6383

South,Week 4,5924

East,Week 1,7463

East,Week 2,6673

East,Week 3,4788

East,Week 4,4583

West,Week 1,5684

West,Week 2,5018

West,Week 3,5285

West,Week 4,10000

29

30

Notes