OBJECT ORIENTED PROGRAMMING: VBA

Similar documents
VBA Collections A Group of Similar Objects that Share Common Properties, Methods and

Advanced Financial Modeling Macros. EduPristine

Civil Engineering Computation

DATA 301 Introduction to Data Analytics Microsoft Excel VBA. Dr. Ramon Lawrence University of British Columbia Okanagan

Unit 12. Electronic Spreadsheets - Microsoft Excel. Desired Outcomes

You can record macros to automate tedious

Excel 2016 Basics for Windows

VBA Excel 2013/2016. VBA Visual Basic for Applications. Learner Guide

Microsoft Excel 2010 Level 1

Using Microsoft Excel

I OFFICE TAB... 1 RIBBONS & GROUPS... 2 OTHER SCREEN PARTS... 4 APPLICATION SPECIFICATIONS... 5 THE BASICS...

Lab 7 Macros, Modules, Data Access Pages and Internet Summary Macros: How to Create and Run Modules vs. Macros 1. Jumping to Internet

Excel 2016 Basics for Mac

Microsoft Excel 2007 Macros and VBA

Read Me First (Excel 2007)

Watch the video below to learn more about the basics of working with cells. *Video removed from printing pages. Understanding cells

Fundamentals. Fundamentals. Fundamentals. We build up instructions from three types of materials

Microsoft Excel 2016 Level 1

Learning Excel VBA. Creating User Defined Functions. ComboProjects. Prepared By Daniel Lamarche

Using macros enables you to repeat tasks much

As you probably know, Microsoft Excel is an

Introduction to Microsoft Excel 2010

Chapter 3: The IF Function and Table Lookup

Getting started 7. Writing macros 23

download instant at

Visual Basic for Applications

Microsoft Excel Microsoft Excel

2. create the workbook file

Functions in Excel. Structure of a function: Basic Mathematical Functions. Arithmetic operators: Comparison Operators:

EXCEL PRACTICE 5: SIMPLE FORMULAS

Introduction to Microsoft Excel 2007

EXCEL BASICS: MICROSOFT OFFICE 2007

Excel Advanced

KEYWORDS DDE GETOBJECT PATHNAME CLASS VB EDITOR WITHEVENTS HMI 1.0 TYPE LIBRARY HMI.TAG

Learning Worksheet Fundamentals

4) Study the section of a worksheet in the image below. What is the cell address of the cell containing the word "Qtr3"?

Agenda. Spreadsheet Applications. Spreadsheet Terminology A workbook consists of multiple worksheets. By default, a workbook has 3 worksheets.

Chapter 13 Creating a Workbook

= 3 + (5*4) + (1/2)*(4/2)^2.

Excel 2016: Part 1. Updated January 2017 Copy cost: $1.50

Microsoft Excel Office 2016/2013/2010/2007 Tips and Tricks

The For Next and For Each Loops Explained for VBA & Excel

Introduction to Microsoft Excel 2010

Excel 2013 Beyond TheBasics

EXCEL BASICS: MICROSOFT OFFICE 2010

Word 2016 Advanced. North American Edition SAMPLE

Moving and copying data

Excel Foundation (Step 2)

Documentation of DaTrAMo (Data Transfer- and Aggregation Module)

Macros enable you to automate almost any task that you can undertake

My Top 5 Formulas OutofhoursAdmin

A cell is highlighted when a thick black border appears around it. Use TAB to move to the next cell to the LEFT. Use SHIFT-TAB to move to the RIGHT.

Advanced Excel Macros : Data Validation/Analysis : OneDrive

Excel Basics Tips & Techniques

Lecture- 5. Introduction to Microsoft Excel

Lesson 18 Getting Started with Excel Essentials

Microsoft Excel Chapter 1. Creating a Worksheet and an Embedded Chart

BASIC EXCEL SYLLABUS Section 1: Getting Started Section 2: Working with Worksheet Section 3: Administration Section 4: Data Handling & Manipulation

Macros enable you to automate almost any task that you can undertake

Within the spreadsheet, columns are labeled with letters and rows are labeled with numbers.

Day : Date : Objects : Open MS Excel program * Open Excel application. Select : start. Choose: programs. Choose : Microsoft Office.

Microsoft Excel 2010 Training. Excel 2010 Basics

The Item_Master_addin.xlam is an Excel add-in file used to provide additional features to assist during plan development.

QUICK EXCEL TUTORIAL. The Very Basics

Excel Conditional Formatting (Mac)

Rev. B 12/16/2015 Downers Grove Public Library Page 1 of 40

Introduction to Microsoft Excel

TUTORIAL FOR IMPORTING OTTAWA FIRE HYDRANT PARKING VIOLATION DATA INTO MYSQL

Rev. C 11/09/2010 Downers Grove Public Library Page 1 of 41

Microsoft Excel - Macros Explained

ABOUT THIS COURSE... 3 ABOUT THIS MANUAL... 4 LESSON 1: MANAGING LISTS... 5

Appendix A1 Visual Basics for Applications (VBA)

ITConnect KEEPING TRACK OF YOUR EXPENSES WITH YNAB

Basic Microsoft Excel Skills

Microsoft Excel Level 2

Rio Hondo Prep Computer Applications Class

Chapter 7. Joining Maps to Other Datasets in QGIS

x, with a range of 1-50 (You can use the randbetween command on excel)

BASIC MACROS IN EXCEL Presented by IGNACIO DURAN

Microsoft Word. An alternative to following these steps are to double click on the Microsoft Word Icon on the desktop.

Making an entry into the CIS Payments workbook

Excel has a powerful automation feature that lets you automate processes that you need to do repeatedly.

Excel Basics 1. Running Excel When you first run Microsoft Excel you see the following menus and toolbars across the top of your new worksheet

Free Microsoft Office 2010 training from MedCerts. Course Outline

COPYRIGHTED MATERIAL. Making Excel More Efficient

PHLI Instruction (734) Introduction. Lists.

Introduction to Microsoft Excel

Basics of Spreadsheet

Jump Right In! Essential Computer Skills Using Microsoft 2013 By Andrews, Dark, and West

A PRACTICAL TUTORIAL TO EXCEL

Excel VBA. Microsoft Excel is an extremely powerful tool that you can use to manipulate, analyze, and present data.

DOWNLOAD PDF EXCEL MACRO TO PRINT WORKSHEET TO

Microsoft Excel 2010 Basic

Outline. Midterm Review. Using Excel. Midterm Review: Excel Basics. Using VBA. Sample Exam Question. Midterm Review April 4, 2014

Text. Text Actions. String Contains

MICROSOFT OFFICE. Courseware: Exam: Sample Only EXCEL 2016 CORE. Certification Guide

Day : Date : Objects : Open MS Excel program. Subject : * Open Excel application. Select : start. Choose: programs. Choose : Microsoft Office

Microsoft Excel 2010 Handout

Technical White Paper

WEEK NO. 12 MICROSOFT EXCEL 2007

Transcription:

Agenda for Today VBA and Macro creation (using Excel) DSC340 Object-Oriented Programming Creating Macros with VBA Mike Pangburn What is O-O programming? OBJECT ORIENTED PROGRAMMING: VBA A programming style that uses objects to comprise programs. Objects: In a pure O-O language, every thing in the program is an object. An object is a data structure consisting of attributes (data fields) and methods (actions). The attributes of the object hold its current information The methods of the object determine what the object can do Different objects types: classes Creating and using objects Each programming environment comes with many different kinds of predefined objects. An object type is called a class. A class is thus some type of object. All objects within a class hold the same kind of information (identical attributes) and can perform the same actions (identical methods). A class is the cookie cutter /template you use to create new object instances. Hollywood analogy: in Battlestar Galactica there are 12 classes of human robots. One of these 12 model types was the Sharon model. You 1 st need a class class Sharon Attributes: height, 3Dbodyshape, faceimage, currentlocation, currentlove, pastexperienceslog Methods: imitatehuman, fallinlove(person), dosecretmission(password) You then declare a new object and can subsequently assign its attribute value and invoke its methods. Example: declaring a new Sharon object, assigning a value, and calling a method Sharon sharonno55 sharonno55.currentlocation = KA.493.X7.1034 sharonno55.fallinlove(helo) 1

Object Oriented Programming Fundamentals VBA: Visual Basic for Applications Appropriate object classes (their attributes and methods) heavily depend on the problem you are working on. Example: A system for a bank: Objects: Customers, Accounts, etc. Attributes: First Name, Last Name, SSN, Address, etc. Methods: Withdraw, Open an account, Deposit, Cash check, etc. VBA is a specialized version of Microsoft s well-known Visual Basic language. VBA is an Object-Oriented language within Microsoft Office suite: Excel, Word, Access, and Power Point. We will focus on Excel. Shortcut to access the VBA interface in Excel: Alt+F11. Excel treats everything in a spreadsheet as objets. So, VBA lets us play with all these objects. Object that we are interested in: Workbooks, worksheets, cells, rows, ranges. There are over 200 different class (types of objects) in Excel. Coding with VBA Problem Definition There are two approaches to write a code in VBA: Standard Coding Macro Recording The Macro approach records a series of mouse-clicks and keyboard strokes. Advantage: Corresponding VBA code is created automatically and recorded for you. Disadvantage: It s limited. To tackle this limitation, we use a mixed approach: First, record a simple macro. Then, tweak it to achieve more complex tasks. We have data spanning 3 columns and 13 rows (C6:F18). Data should be stored in the given range in order to use it for other application. Unfortunately, there are some errors in the data entry process, so some of the rows are shifted to the right by one column. Problem Definition Our First Macro We have data spanning 3 columns and 13 rows (C6:F18). Data should be stored in the given range in order to use it for other application. Unfortunately, there are some errors in the data entry process, so some of the rows are shifted to the right by one column. Our job is to correct all these mistakes: First, record a simple macro that correct a specific row (say Row 8). Then, tweak it to make correction in any given row. Finally, we let the code check any mistake and correct it. While doing this, we learn how to Declare and name variables. Create Subroutines and Functions (We ll learn what they are shortly). Use conditional statements. Create repetitions. Download and open VBA_Example_class.xlsm In Excel 2010, we should save the file as a Macro Enabled Workbook (i.e., in the.xlsm format). 2

Our First Macro Find the Macros option under the Excel 2010 View tab to record a VBA macro. Let s call our Macro Shifter. We want our macro to do the following: Select the range D8:F8. Cut the selected cells. Select cell C8. Paste the cut cells. To see the VBA code generated by your actions, go into VBA (Alt+F11) and then near the upper left of the window expand the Modules folder and double-click on Module1. Subroutines Notice that the code starts with Sub command and ends with command. Sub refers to the Subroutines. Subroutine: A portion of code within a larger program that performs a specific task and is relatively independent of the remaining code. We can use a subroutine in a different subroutine by calling it. e.g., Call Shifter(). Execution of Subroutines Subroutines with Input Arguments The limitation of Shifter is that it only corrects Row 8. We can solve this by creating a subroutine which will take a row number as an input parameter. Sub ShiftOneColumn (RowNum As Integer) CODE BLOCK Each line of a subroutine is executed sequentially. Let s see how our macro is executed. (The first three green lines following each are simply comments/documentation.) The real first line is Range("D8:F8").Select, and it selects the cells we want to select. The second line, Selection.Cut, cuts the selected cells. The third line, Range("C8").Select, selects the cell C8. Finally, the last line, ActiveSheet.Paste, pastes the cut values to the selected cell of the worksheet. RowNum is the input variable. We name it. As Integer part declares the data type of our input variable. Common Data Types: Data Type Boolean Integer Double String Description Holds either TRUE or FALSE value. Integers between -32000 and 32000 Double precision numbers, can hold fractional numbers (The range of double number is very large) A set of characters (like sentences) Shifting Any Given Column Sub ShiftOneColumn (RowNum As Integer) Range("D" & RowNum & ":F" & RowNum).Select Selection.Cut Range("C" & RowNum).Select ActiveSheet.Paste We now have a subroutine that can correct any given row. We want to apply this subroutine to any rows between 6 and 18. We use a loop (e.g., a FOR-NEXT Loop) for this task: For-Next Loop Syntax For varname=start_val To end_val Step step_size CODE BLOCK Next varname How do we tell VBA to shift the row according to our input, RowNum? Currently, we select cells D8,E8,F8 by writing "D8:F8". We will construct that D#:F# syntax, for our row # (i.e., RowNum) Range("D" & RowNum & ":F" & RowNum).Select The above code assigns the value of variable varname to start_val. Then, executes the code inside the loop. After that, increases the value of variable varname by step_size And, runs the code again. Repeats that until the value of variable varname reaches end_val. In Excel and VBA the & operator simply combines ( concatenates ) text together 3

Variable Declaration Sub ShifterLoop The subroutine ShiftOneColumn requires an integer input. We decided to introduce something called RowNum which stores a row number. We want the data type for RowNum to be Integer. The VBA interpreter will attempt to guess (scary!) the data type if you forget to declare your variables. To avoid that problem, we need to define the variables we use properly: Let s create our FOR-NEXT Loop. The variable whose value we change is RowNum. The Start value is 6. The End value is 18. And, the Step Size is 1. In each step, we call the subroutine ShiftOneColumn. Notice that we have started to use the value called RowNum that we introduced. Variable Declaration in VBA Dim varname As datatype Some rules about variable declaration: Variables names have to start with a letter, and have no spaces. VBA is not case sensitive (RowNum and rownum are the same). Names that are more than one word are usually written with the first letter of words capitalized; it s not required but it s fairly standard practice). Checking If First Column is Empty So, we add a line before the loop where we declare our variable RowNum. Sub ShifterLoop Dim RowNum As Integer We need to check whether the first column of a row is empty or not. VBA s conditional statement IF-THEN-ELSE allows us to achieve this goal. IF-THEN-ELSE Syntax If test_cond Then CODE BLOCK executed if test_cond holds Else CODE BLOCK executed if test_cond fails A Function to Check the First Column More on Functions vs. Subroutines We could write our conditional statement to check the first column within the subroutine, but we will define a separate Function for the checking task. Functions are very similar to the subroutines. Then, why a function? Unlike a subroutine, but Functions return a value. Useful for reporting the result of a calculation or other results. Our function will return 1 if the first column is empty 0 otherwise. Functions are not always the right choice: A function cannot directly write data back to the spreadsheet. We can write data to the spreadsheet via subroutines. Easiest way: How to write data to cells Cells(row_num,col_num).Value= x e.g., Cells(10,3).Value= "Ducks Rock" writes Ducks Rock to the cell C10. (Try it!) In this example, our function doesn t need to change the value of cell, but our function does return a value. 4

A Function to Check the First Column Using the Check Function in the Main Subroutine Let s go back to our task: Creating a function to check the first column. We name our function as CheckColOne. What is our input argument? Row Number. Function to check the first column Function CheckColOne (RowNum as Integer) If Cells(RowNum,3).Value="" Then CheckColOne=1 Else CheckColOne=0 End Function How do we check if the first column is empty? We can use Cells(row_num,col_num).Value. Then, check whether it is empty. We know the row number: It s our input argument, RowNum. The column number is 3 since the first column of data is in Column C. So, our test condition is if Cells(RowNum,3).Value="". Sub ShifterLoop () Dim RowNum As Integer If CheckColOne(RowNum) Then Practice: Extending our program How would we extend our program if we wanted to have the program highlight each moved row with a yellow background? Remember the approach most business people using VBA take: Perform Macro Recording to start Use/modify the resulting code 5