Introduction To VBA (Visual Basic For Applications .

2y ago
2 Views
2 Downloads
2.71 MB
71 Pages
Last View : 29d ago
Last Download : 3m ago
Upload by : Sabrina Baez
Transcription

10/26/2016Introduction to VBA (Visual Basic ForApplications) Programming Origins of VBA, creating and running a VBA programVariables & constantsInteractive programsFormatting documentsDebugger basicsSecurityIntroduction to program documentationOnline support: A.S.I.C. Beginner’s All-Purpose Symbolic Instruction Code (BASIC)– From: www.acm.org (original full article: http://time.com/69316/basic/) A widely used programming language It was relatively simple to learn (statements were “English-like”e.g., “if-then”) Widely popular and it was commonly packaged with newcomputers in the 1970’s and 1980’s (A then relatively unknown company: Microsoft got it’s initialcash inflows and reputation producing several versions of thelanguage)Administrative and course introduction1

10/26/2016Microsoftorigins: if thereis timeB.G.www.colourbox.comVisual Basic A newer programming language developed by Microsoft It was designed to make it easy to add practical and usefulfeatures to computer programs e.g., programmers could add agraphic user interface, database storage of information etc. Also it can take advantage of the built in capabilities of thevarious versions of the Windows operating system– Why write a feature of a program yourself when it already “comes withthe computer” For more information:– spxAdministrative and course introduction2

10/26/2016Visual Basic For Applications (VBA) Shares a common core with Visual Basic.– Statements ‘look’ similar Unlike Visual Basic, VBA programs aren’t written in isolation(creating a program just for it’s own sake).– Most programs are written to be standalone: a computer game can berun without (say) running a web browser or MS-Office. VB Visual Basic, VBA Visual Basic for Applications Each VBA program must be associated with a ‘host’ application(usually it’s Microsoft office document such as MS-Word butother applications can also be augmented by VBA programs).– The host application is enhanced or supplemented by the VBA program– “Why doesn’t this stupid word processor have this feature?!!”- Now you can add that feature yourself using VBAVisual Basic For Applications (VBA): 2 Important! Because every VBA program must be run withinthe context of host application when you are learning to writeyour programs do not open up an important MS-Worddocument and run your programs.– The host program often needs an Word document in order to run certaincapabilities.– VBA programs often change documents (formatting, style, text).– Therefore use only small ‘test’ MS-Word documents when running yourVBA programs otherwise your information may be lost or corrupted.Administrative and course introduction3

10/26/2016Macros Macro: a sequence of keystrokes or mouse selections(instructions to the computer) that can be repeated over andover– MS-Office can be augmented by writing Macros (essentially computerprograms) that will run either for multiple documents or only for aparticular document.– In this class we will focus solely on MS-Word macro programming VBA (as guessed) is an example of a macro programminglanguage e.g., you can write a program that includes a series offormatting and other commands that you frequently carry outin Word documents Write the commands once in the form of a program and justre-run this program instead of re-entering each commandMacros And The Web-Based Office According to Microsoft macros are not accessible via theironline Office b6?CorrelationId 917b1609-97e9-4cc7-9eeb-d188939ad740&ui enUS&rs en-US&ad US Result: use a computer wit 0329.html– http://support.microsoft.com/kb/224567 Macro viruses aren’t just “ancient history”, take the potentialthreat seriously!– http://www.symantec.com/avcenter/macro.html– cyclopedia/search.aspx?query Virus– http://ca.norton.com/search?site nrtn en CA&client norton&q macro virusAdministrative and course introduction9

10/26/2016Enabling Macros To Run If you can' t run macros in MS-office (you see odd errormessages) then examine the "Trust Center“ settings in Word1. Select the ‘File’ ribbon2. Select ‘options’Enabling Macros To Run (2)3A) Select “Trust Center”Administrative and course introduction3B) Select “Trust Center Settings”10

10/26/2016Enabling Macros To Run (3)4A) Select “Macro Settings”4B) Select “Disable all macros with notification”MoresecureLesssecure5) Exit MS-Word (close ALL documents)Enabling Macros To Run (4) The default setting for MS-Word should already be set to“disable macros with notification” but these steps will allowyou to use machines set differentlyAdministrative and course introduction11

10/26/2016Effect: Opening Word Documents Using this setting will disable all macros by default (saferapproach) but you can still enable the macros as the documentis opened.JT’s caution You should not casuallyselect this option for all MSWord documents It’s recommended that youONLY enable macros youhave created (or the lectureexamples)Macro Security DO NOT take the ‘easy’ way outMoresecureNO!LesssecureFor more HA010031071.aspxAdministrative and course introduction12

10/26/2016Creating Macros1. Record the macro automatically: keystrokes and mouseselections will be stored as part of the macro2. Manually enter the Macro (type it in yourself into the VBAeditor)Recording Macros Developer ribbon– “Record Macro”– Recording detailsWhat toname themacroWhere tostore themacroAdministrative and course introduction13

10/26/2016Naming The Macro: Conventions Part of your assignment marks will be awarded according tohow well your programs conform to stylistic conventionssuch as naming conventions employed.– Macros should be given a good self-explanatory name: describes thepurpose of the program e.g., ‘formatting resume headings’– Additional information about the program can be provided in the‘description’ field but for this class we will do this using ‘programdocumentation’ (described later). Language requirements (macro name): Must start with an alphabetic letter, after than any combination of lettersand numbers may be used OK: “assigment1”, “a2939”Not OK: “1assignment”, “*assignment” Maximum length of 80 characters It cannot contain spaces, punctuation or special characters such as # or !–‘resume headings’ (Not Allowed: space character)–‘macros!’ (Not Allowed: special character) Can contain underscores (separate long names)The First Simple Macro With word processing there’s sometimes a need to applymultiple formatting styles (bold, italics, underline) to highlighted text Manually applying the required formatting to each block oftext can be tedious– Recall: Macros can be used to automate or shorten some tasks This first example macro program will be used to show:– How to create a VBA macro for MS-Word– How to automate a task using a macroAdministrative and course introduction14

10/26/2016Recording A Simple Macro (Of course a macro isn’t needed to use this formatting effectbut it’s easiest to start with a simple example). Bold face highlighted text.– Select the developer tab and press recordRecording A Macro (2) Give the macro a self explanatory name and press ‘OK’ (recordingbegins). Note: record the macro in the current document and not “Alldocuments” (Important!)Administrative and course introduction15

10/26/2016Recording A Macro (3) Select whatever options you want to add to the recording ofthe macro– In this case you would select bold font– All commands have been entered so you can stop the recordingRunning A Recorded Macro Under the Developer ribbon select ‘macros’ Select the macro and then ‘run’ itAdministrative and course introduction16

10/26/2016Running A Recorded Macro (2) In this case nothing happened?– This macro changes selected/highlighted text to bold– You need to select some text before running the macroRunning A Recorded Macro (3) After selecting the text and running the macro again, whatevertext was highlighted now becomes bold.Administrative and course introduction17

10/26/2016Recording Macros: Additional Comments Don’t rely on creating all your macros by recording them. Drawbacks:– (Problem in terms of this class) to demonstrate your understanding ofconcepts you will be asked to manually write VBA code You won’t be adequately prepared if you rely on automatically recordingyour programs– (Problem with doing this in real work) The automatically generatedprogram code automatically is larger and more complicated than isnecessary “Bloated” code Look under search terms such as bloated "vba code" recorded forexamples of why automating recording VBA programs can be problematic.Auto Generated VBA Program: 24 LinesSub heading()With Selection.ParagraphFormat.LeftIndent InchesToPoints(0).RightIndent InchesToPoints(0).SpaceBefore 0.SpaceBeforeAuto False.SpaceAfter 6.SpaceAfterAuto False.LineSpacingRule wdLineSpaceSingle.Alignment wdAlignParagraphCenter.WidowControl True.KeepWithNext False wdOutlineLevelBodyText.OutlineLevel.KeepTogether False.CharacterUnitLeftIndent 0.PageBreakBefore False.CharacterUnitRightIndent 0.NoLineNumber False.CharacterUnitFirstLineIndent 0.Hyphenation True.LineUnitBefore 0.FirstLineIndent InchesToPoints(0).LineUnitAfter 0.MirrorIndents False.TextboxTightWrap wdTightNoneEnd WithEnd SubAdministrative and course introduction18

10/26/2016VBA Statements Actually Needed: 1 LineSub r 6End SubRecording Macros: Additional Comments Benefits:– You can use the macro code that is automatically generated in order tolearn how to do manually.– Sometimes this is very useful if you don’t know the wording of acommand or how to access a property.– Example (VBA program code for the previous example) Record the commands for the macro Then view the commands so you can learn how to do it manuallySub AutoGeneratedFontChange()Selection.Font.Bold wdToggleEnd SubAdministrative and course introduction19

10/26/2016Recording Macros Bottom line: use it for learning “how to do” things Don’t:– Just use the auto-generated code to study for the exam without creatingany code of your code– Just hand in the auto-generated VBA code for your assignment While taking this course: Use the auto-generated code tofigure out how to “type the program from scratch” yourself (Iwill show how to do this shortly) After this course is done: if ever you find your usage of Officetedious and repetitive (multiple clicks) then you can record allthose steps into one macro!The Visual Basic Editor You don’t need to familiarize yourself with every detail of theeditor in order to create VBA programs. Just a few key features should be sufficient Starting the editor:– Because VBA programs are associated with an office application open theeditor from MS-Word– Click the “Visual Basic” icon under “Developer”Administrative and course introduction20

10/26/2016Overview Of The Important Parts Of The VBAEditorSaveCut, copy,pasteFind,replaceHelp lookupProgrameditorUndo,redoExport:Useful fortransferring or

Viewing The Developer Ribbon MS -Word 2013): 3 This should add a new ribbon Developer _ Alternate: View And Run Macros You may or may not be able to edit the MS-Word ribbon with some compu

Related Documents:

Updated to include preliminary information on the VBA language from the pre-release version of VBA 7. 3/15/2010 1.0 Major Updated to include information on the VBA language as of VBA 7. 3/15/2012 1.01 Major Updated to include information on the VBA language as of VBA

13.2. Excel and VBA Implementation 248 APPENDIX A VBA Programming 255 A.1 Introduction 255 A.2 A Brief History of VBA 255 A.3 Essential Excel Elements for VBA 256 A.3.1 Excel Cell Reference 257 A.3.2 Excel Defined Names 261 A.3.3 Excel Worksheet Functions 264 A.4 The VBA Development Enviro

begin using VBA and writing a simple macro. You access VBA through Inventor using the Macro Visual Basic Editor command in the Tools menu, or by pressing Alt-F11. Once the VBA environment is open, the first thing I recommend you do is change some of the VBA settings. In the VBA environment run the Options command from the Tools menu. Change the

Programming: VBA in MS Office – An Introduction 3 IT Learning Programme 1.4. What is VBA? VBA is a high-level programming language that sits behind the Microsoft Office suite of applications. It is made available, through the built-in VBA Editor in each applicable application, to the end user to create code that can be executed within

VBA stands for Visual Basic for Applications. It is a custom version of the venerable Visual Basic programming language that has powered Microsoft Excel's macros since the mid-1990s. IMPORTANT Please ensure any examples or topics created within the excel-vba tag are specific and relevant to the use of VBA with Microsoft Excel.

We can use VBA in all office versions right from MS-Office 97 to MS-Office 2013 and also with any of the latest versions available. Among VBA, Excel VBA is the most popular one and the reason for using VBA is that we can build very powerful tools in MS Excel using linear programming. Application of VBA

VBA4-Using Cell Formulas in VBA Page 3 of 7 O:\COURSES\VBA\Online VBA\VBA4-Using Cell Formulas in VBA.docx 8. While ActiveCell.Value "" is the way to loop as long as there is a value in the current cell. You also might use an offset: While ActiveCell.Offset(0,-1).Value "" will test the column to the left of the current column.

Jun 05, 2004 · extends primarily to functionality found in worksheets. Excel workbooks with Visual Basic for Applications (VBA) macros embedded do not function in Calc, even though VBA and StarBasic (SB) are syntactically the same. The reason Excel/VBA workbooks do not work under Calc/SB is due to the differences in the underlying object models for Excel and .