DATA 301 Introduction To Data Analytics - Excel VBA

2y ago
135 Views
5 Downloads
1.50 MB
50 Pages
Last View : 23d ago
Last Download : 3m ago
Upload by : Allyson Cromer
Transcription

DATA 301Introduction to Data AnalyticsMicrosoft Excel VBADr. Ramon LawrenceUniversity of British Columbia Okanaganramon.lawrence@ubc.ca

DATA 301: Data Analytics (2)Why Microsoft Excel Visual Basic for Applications?Microsoft Excel VBA allows for automating tasks in Excel and providesa full programming environment for data analysis.Excel VBA is commonly used in high finance and frequency tradingapplications for creating and validating financial models.Using Excel VBA will be our first practice with programming and allowus to explore fundamental programming concepts of commands,variables, decisions, repetition, objects, and events.

DATA 301: Data Analytics (3)Excel Visual Basic for Applications (VBA)Visual Basic for Applications (VBA) is a programming languageallowing users to build their own functions, automate tasks inMicrosoft Office, and develop customized code.The language has been part of almost all versions of Office for over 20years.VBA allows for expanding the capabilities of Excel and adding userinterface elements (buttons, lists) to your spreadsheet.

DATA 301: Data Analytics (4)MacrosA macro is a recorded set of actions that is saved so that they can beeasily executed again.If you do the same set of actions repetitively, then creating a macroallows for doing all those actions with one command.Macros are accessible under the View tab in the Macros group orthe Developer tab.Macros are converted into VBA programs.

DATA 301: Data Analytics (5)Developer TabThe Developer tab containsicons for performing VBA andmacro development.To add the Development tab,go to File, Options,Customize Ribbon andmake sure it is checked besideDeveloper.

DATA 301: Data Analytics (6)Recording a MacroTo record a macro, under View select, Macros - Record Macro. Excel will record your actions until you select Stop Recording. Note: Cursor movement is not captured.Macro names cannot contain spaces or beginwith a number.It is recommended to useCtrl Shift Key for a Shortcut key so thatyou do not override built-in shortcuts.Macros can be created in a given workbook ora Personal Workbook allowing them to beused in multiple workbooks.

DATA 301: Data Analytics (7)Using a MacroUse a macro in the following ways:1) With the shortcut key if defined2) Assign a macro to a button or on the toolbar3) Under Macros, Select View Macrosthen pick the macro and Run.

DATA 301: Data Analytics (8)Macros QuestionQuestion: Select a TRUE statement.A) A macro can be created without assigning it a shortcut key.B) A macro will record cursor movements.C) Macros can be created in an individual workbook or in a personalmacro workbook so they can be used in multiple workbooks.D) A macro can have only one command it executes.

DATA 301: Data Analytics (9)Adding Macro to Quick Access ToolbarAdd a macro to The Quick Access Toolbar under File, Options,Quick Access Toolbar.macro icon

DATA 301: Data Analytics (10)Try it: MacrosQuestion: Create a macro that does the following tasks: Bolds the cell and makes the font Courier 20.Sets the cell background to orange.Centers the text in the cell.Use a shortcut of Ctrl Shift b.Add it to the Quick Access Toolbar.Try-out your macro using the shortcut key,toolbar, and from the macro dialog.

DATA 301: Data Analytics (11)Saving Workbook with MacrosExcel now forces workbooks with macros to be saved in Excel MacroEnabled Workbook (*.xlsm) format.Saving a workbook with macros in regular format gives this error:

DATA 301: Data Analytics (12)Macro SecuritySince macros can execute any code, they have been a target for viruswriters. Understanding the source of the Excel spreadsheet thatcontains macros is important when deciding to run them or not.Excel has macro security settings to allow you to enable or disablerunning macros. Spreadsheets with macros often will generate awarning when opening them:

DATA 301: Data Analytics (13)Macro Security SettingsThe default security isDisable all macros withnotification that preventsmacros from running butdisplays a warning allowingyou to enable them.One of the biggest issueswith macros is security andmaking sure you are onlyusing macros from atrusted source.

DATA 301: Data Analytics (14)Macros: ImplementationMacros are converted to Visual Basiccode.Can edit macro code and create yourown code.Under the Developer tab, selectMacros then Edit macro to modifythe code.

DATA 301: Data Analytics (15)Visual Basic EditorVisual Basic Editor (VBE) allows editing visual basic code and is acomplete integrated development environment (IDE).Users can create and edit macros as well as other Visual Basic codewith the editor.To open the VBE, under Developer tab - Visual Basic orAlt F11.

DATA 301: Data Analytics (16)Visual Basic Editor ScreenshotProject ExplorerwindowCode windowPropertieswindowImmediate window

DATA 301: Data Analytics (17)Object BrowserObject browser allows for exploring objects and methods (theapplication programming interface (API)) of Excel VBA. Open with F2.

DATA 301: Data Analytics (18)Macro Code in Visual Basic EditorSubroutine with name and no argumentsComments start with 'Every statement is on itsown line.Dot notation toseparate "items"(objects, methods,properties).

DATA 301: Data Analytics (19)WITH Statement in Visual Basic CodeWITH syntax simplifies typing sameobject many times.These lines all apply toSelection.Font.

DATA 301: Data Analytics (20)Visual Basic Editor: Immediate WindowThe Immediate window allows entering of single line commands. Use PRINT or ? In code, use Debug.Print to print to immediate window.

DATA 301: Data Analytics (21)Try it: Immediate WindowQuestion: Try do these actions using the immediate window: 1) Print "Hey There!"2) Calculate the answer of 765 * 39.3) Select a cell then call the macro RedItalics.4) Change the value of cell B4 to "DATA".5) Change the value of cell A6 to 100.

DATA 301: Data Analytics (22)Challenge Try it: Create Macro in VBEQuestion: Copy the MyFormat macro and edit to produce a newmacro called RedUnderline that: Underlines the text in the cell. Makes the cell background red. If the cell was bold or italics before, resets to not have bold and italics.Hints: Underline property in Excel is Font.Underline and can set to constantxlUnderlineStyleSingle. Can change background color with Interior.Color and set toRGB(redValue, greenValue, blueValue) where the color values arenumbers from 0 to 255.

DATA 301: Data Analytics (23)Introduction to ProgrammingAn algorithm is a precise sequence of steps to produce a result. Aprogram is an encoding of an algorithm in a language to solve aparticular problem.There are numerous languages that programmers can use to specifyinstructions. Each language has its different features, benefits, andusefulness. We will start with Excel VBA but also study Python and R.The goal is to understand fundamental programming concepts thatapply to all languages.

DATA 301: Data Analytics (24)VariablesA variable is a name that refers to a location that stores a data value.Location Age18Value (cute )IMPORTANT: The value at a location can change using initialization orassignment.

DATA 301: Data Analytics (25)Variable AssignmentAssignment using an sets the value of a variable.Example:num 10num Range("A1").Valuenum 20

DATA 301: Data Analytics (26)Excel VariablesEvery variable in Excel has a name and a data type. Variables increase code efficiency and readability. Data types: Boolean, Currency, Date, Double, Integer, Long,Object, String, Variant (any type)Example:Dim num As Integer

DATA 301: Data Analytics (27)CollectionsCollections are variables that store multiple data items. Data itemscan either be indexed (selected) by name or ksheets is a collection as there may be multiple worksheets inthe workbook. Select one by name or number (starting with 1).

DATA 301: Data Analytics (28)Variables QuestionQuestion: How many of the following statements are TRUE?1) A variable name cannot change during a program.2) A variable value cannot change during a program.3) A collection is a variable that can store multiple data items.4) A value in a collection can be retrieved by name or by index starting from0.5) In Excel, variables are declared using DIM.6) In Excel, variables are declared with a data type.A) 0B) 1C) 2D) 3E) 4

DATA 301: Data Analytics (29)DecisionsDecisions allow the program to perform different actions in certainconditions. Logical operators: AND, OR, NOTExcel decision syntax:If condition ThenstatementEnd IfIf condition ThenstatementElsestatementEnd If

DATA 301: Data Analytics (30)Question: DecisionsQuestion: What is the output of the following code?A) 100B) 40C) 20D) error – no output

DATA 301: Data Analytics (31)Try it: DecisionsQuestion: Create a method called EchoDecision that asks user aYes and No question and outputs a message either "Yes" or "No"depending on what they chose.

DATA 301: Data Analytics (32)Loops and IterationA loop repeats a set of statements multiple times until some conditionis satisfied. Each time a loop is executed is called an iteration. A for loop repeats statements a given number of times.Excel for loop syntax:Dim i as IntegerFor i 1 To 5Debug.Print iNext i

DATA 301: Data Analytics (33)Question: LoopsQuestion: How many numbers are printed with this loop?A) 11B) 10C) 0D) error – no output

DATA 301: Data Analytics (34)Try it: LoopsQuestion: Create a method called TryFor that prints the numbers 1to 20. Challenging variants: Print the numbers from 10 down to 1. Print only the even numbers from 1 to 10.

DATA 301: Data Analytics (35)User-Defined Functions (UDFs)A user-defined function is your own Excel function that can be used informulas like built-in functions.A UDF must return a number, string, array, or Boolean.A UDF cannot change the Excel environment including the current cellsor other cells (e.g. change formatting).

DATA 301: Data Analytics (36)UDF ExampleUDF doubleIt will double the input argument.

DATA 301: Data Analytics (37)UDF Example – Sum Cells by Background Color

DATA 301: Data Analytics (38)Try it: UDFQuestion: Create a UDF called CountNum that will return a count ofthe number of digits (0 to 9) in a string.

DATA 301: Data Analytics (39)Advanced: Object-Oriented ProgrammingObject-oriented programming structures code as object, classes,methods, and properties. This organization makes it easier tounderstand and construct large programs.An object is an instance of a class that has its own properties andmethods that define what the object is and what it can do.A class is a generic template (blueprint) for creating an object. Allobjects of a class have the same methods and properties (although theproperty values can be different).A property is an attribute or feature of an object.A method is a set of statements that performs an action.

DATA 301: Data Analytics (40)Excel ObjectsExcel structures everything as a hierarchy of objects, and commandsare done by running a method of an object.An object may contain other objects as well as methods andproperties. A dot "." is used as a separator between objects andsubobjects, methods, and properties.Examples: Top-level object: Application Workbook – individual Excel file Worksheet - sheet in a ro").Range("A1").Value

DATA 301: Data Analytics (41)Excel Range ObjectThe Range object selects a cell or group of Font.Italic True

DATA 301: Data Analytics (42)Excel Object MethodsMethods perform an action.Example:Worksheets("macro").Activate

DATA 301: Data Analytics (43)Object-Oriented QuestionQuestion: How many of the following statements are TRUE?1) A method can have no parameters.2) Two objects of the same class have the same properties.3) Two objects of the same class may have different values for theirproperties.4) Workbook is the top-level object in Excel.A) 0B) 1C) 2D) 3E) 4

DATA 301: Data Analytics (44)Try it: Excel ObjectsQuestion: Using the Immediate window try to perform the followingactions with methods on Excel objects:1) Switch the active worksheet to form.2) Switch the active cell to macro sheet A4.3) Use msgbox to display value in current cell (ActiveCell).

DATA 301: Data Analytics (45)Forms and Input ControlsExcel allows the creation of forms with controls for a better interface.Two types of controls in Excel: Form controls – default ActiveX controls – allow more flexibility and customizationControls can be inserted from the Developer tab. Select Insert, pickcontrol, and then click and drag the size and shape of the control onthe spreadsheet.

DATA 301: Data Analytics (46)Input Controlstextboxdrop-downlist boxcheckboxbuttonradio buttons

DATA 301: Data Analytics (47)EventsAn event is a notification to your program that something hasoccurred.Events in Excel: add a worksheetdouble-click on a cellchange a cell valuecalculating a formulaclick on a button (can execute a macro)Worksheet-level events on a particular worksheet and workbook levelevents for entire file.

DATA 301: Data Analytics (48)ConclusionMicrosoft Excel VBA allows for automating tasks in Excel and providesa full programming environment for data analysis.Macro record a set of actions so they can be easily executed again. Be aware of security risks when using macros.The Visual Basic Editor (VBE) is a complete integrated developmentenvironment for editing macros, user-defined functions, and addingforms and controls that dynamically respond to events.Excel VBA uses object-oriented programming that structures code asobject, classes, methods, and properties. A developer can control andautomate everything with Excel using VBA.

DATA 301: Data Analytics (49)Objectives List some reasons to use Excel VBADefine macro and explain the benefit of using macrosBe able to record and execute a macroExplain the security issues with macros and how Excel deals with themList and explain the use of the four main windows of the Visual Basic EditorExplain the role of the object browserExplain and use the WITH statement syntaxBe able to write simple macros using the VBEDefine: algorithm, program, languageDefine: object-oriented programming, object, class, property, methodUnderstand and use dot-notationUse the Range object to select a group of cellsDefine: variable, value, location

DATA 301: Data Analytics (50)Objectives (2) Create and use Excel variablesExplain how a collection is different from a typical variableUse If/Then/Else syntax to make decisionsUse For loop for repetitionCreate user-defined functions and use them in formulasDefine: eventList some typical user interface controlsUnderstand that Excel allows for forms and controls to be added to a worksheetwhich respond to events

Microsoft Excel VBA allows for automating tasks in Excel and provides a full programming environment for data analysis. Excel VBA is commonly used in high finance and frequency trading applications for creating and validating fina

Related Documents:

ref. part no. part description comments revision dwg 70942 image no. 1. 301-540h dozer blade hitch 2. 301-541h pivot frame 3. 301-542h 3.0 pivot pin 4. 301-548h 84" dozer blade 4. 301-549h 96" dozer blade 5. 301-601d float bushing 6. 301-683d 3.0 pivot thrust washer 7. 301-686d pin cap 8. 301-691d tilt pin retainer 9. 301-697d guide plate shim 10. 301-698d guide plate 11. 800-001c grease zerk .

Ⅰ. To start FC-301/D Program Software and read the parameters of FC-301/D RF Link Module Step 1: Make sure the radio FC-301/D is in program status (pin8 SW of CON1(DB9) in low level-GND) and the connection is ready between FC-301/D and PC via program cable. Step 2: Double click ‘QuickSet.exe’ for FC-301/D. It will enter into program

St. Columba Oxon Hill Prince George’s (301) 567-5506 301-567-6546 38 St. Dominic (Mission) Aquasco Prince George’s (240) 681-3551 301-579-0019 5 St. Edward the Confessor Bowie Prince George’s (301) 249-9199 301-249-1303 11 St. Elizabeth Rockville

Brookside Gardens! MontgomeryParks.org THE MARYLAND-NATIONAL CAPITAL PARK AND PLANNING COMMISSION NEW Improved ActiveMONTGOMERY Website, see page 9 - - - - . School of Botanical Art : 301-962-1470 & Illustration : Volunteer Ofce ; 301-962-1429 : Gift Shop ; 301-962-1448 : Facility Rental ; 301-962-1404 : McCrillis Gardens ; 301-962-1455 :

Page 3 National Training Institute Tim Strickland, Director NTI Operations (301) 715-2347 Denise Jenkins, Meeting & NTI Coordinator (301) 715-2344 Virginia Kingsley, HR & NTI Coordinator (301) 715-2345 Order Fulfillment Center Wayne Brown, Warehouse Manager (301) 715-2386 Materials Handler Team (301) 715-2372

6406 Winston Drive Country Club Village Bethesda MD 20817 42 160700671971 Douglas Construction Group LLC 8429 Fox Run, Potomac, MD 20854 (301)983-6947 doug@dcghomes.com RE/MAX Realty Services RBE1 4825 Bethesda Avenue, Suite 200, Bethesda, MD 20814 (301)652-0400 (301)347-1623 Jeremy Lichtenstein 91649 (301)252-0389 (301)347-4121 .

work/products (Beading, Candles, Carving, Food Products, Soap, Weaving, etc.) ⃝I understand that if my work contains Indigenous visual representation that it is a reflection of the Indigenous culture of my native region. ⃝To the best of my knowledge, my work/products fall within Craft Council standards and expectations with respect to

Chapter 301 Design and Maintenance Coordination WSDOT Design Manual M 22-01.11 Page 301-3 July 2014 301.02(2) Communicating Expectations Project design is heavily influenced by the subprogram and scope of a particular project. While this becomes a learned experience within engineering design, maintenance staff does not