VBA Navigation, Conditionals, and Boxes. VBA Navigation.

Slides:



Advertisements
Similar presentations
Lesson 12 Getting Started with Excel Essentials
Advertisements

Microsoft Office XP Microsoft Excel
Object Oriented Programming A programming concept which views programs as objects with properties and ways to manipulate the object and the properties.
Visual Basic for Applications. What it does Extends the features and built in functions of Excel – Create and run VB procedures – Some may be easy to.
Office 2003 Post-Advanced Concepts and Techniques M i c r o s o f t Excel Project 7 Using Macros and Visual Basic for Applications (VBA) with Excel.
Using Macros and Visual Basic for Applications (VBA) with Excel
Developing an Excel Application
XP New Perspectives on Microsoft Excel 2003, Second Edition- Tutorial 8 1 Microsoft Office Excel 2003 Tutorial 8 – Developing an Excel Application.
3-dimensional formula A formula that refers to cells in other worksheets.
Excel Understanding Excel Fundamentals Microsoft Office 2010 Fundamentals 1.
Objectives Understand the software development lifecycle Perform calculations Use decision structures Perform data validation Use logical operators Use.
Excel Lesson 1 Excel Basics. Task 1  Goals  Learn about Excel  Start Excel  Explore the Excel screen  Explore the Excel workbook  Explore the worksheet.
Tutorial 12: Enhancing Excel with Visual Basic for Applications
Writing VBA Macros Record a new Macro, recording only the name, shortcut and description Stop recording Open macro for editing and enter VB code Test.
Microsoft Excel 2003 Illustrated Complete with Excel Programming.
Macros Excel built-in functions are great but limited Macros are a means for the user to define new functions A macro is a single command that automates.
Repeating Program Instructions Chapter Microsoft Visual Basic.NET: Reloaded 1.
Adding Automated Functionality to Office Applications.
Moving data on the worksheet Copying and Pasting Data, Slide 1Copyright © 2004, Jim Schwab, University of Texas at Austin Like other windows applications,
COMPREHENSIVE Excel Tutorial 8 Developing an Excel Application.
Exploring Microsoft Excel 2002 Chapter 8 Chapter 8 Automating Repetitive Tasks: Macros and Visual Basic for Applications By Robert T. Grauer Maryann Barber.
USING WORKSHEETS TO MAKE BUSINESS DECISIONS BY DR. ENNIS - COLE.
WORKING WITH MACROS CHAPTER 10 WORKING WITH MACROS.
McGraw-Hill/Irwin Copyright © 2013 by The McGraw-Hill Companies, Inc. All rights reserved. Extended Learning Module M Programming in Excel with VBA.
Saeed Ghanbartehrani Summer 2015 Lecture Notes #4: Working with Variables and User Interfaces IE 212: Computational Methods for Industrial Engineering.
© McGraw-Hill Companies, Inc., McGraw-Hill/Irwin Extended Learning Module M Programming in Excel with VBA.
McGraw-Hill/Irwin Copyright © 2013 by The McGraw-Hill Companies, Inc. All rights reserved. Extended Learning Module M Programming in Excel with VBA.
IN THE NAME OF ALLAH UserForms on VBA Lab 06 Tahani Al_dweesh.
Introduction on VBA Lab 05 ins.Tahani Al_dweesh. Lab Objectives Introduction Calculation with VBA Storing and Retrieving Variables in a Worksheet Using.
Week 8.  Recap  User Forms  Input Validation Message Boxes Input Boxes  Conversion Functions.
University of Toronto at Scarborough © Andria Hunter, Kersti Wain-Bantin CSCA01 VBA 1 Lecture Outline Record macro and examine VBA code VBA Editor (IDE)
Spreadsheet A spreadsheet is the computer equivalent of a paper ledger sheet. It consists of a grid made from columns and rows. It is an environment that.
 An object-oriented programming language ◦ Instructions for the manipulation of objects ◦ A structured way to provide instructions to Excel  Excel has.
Copyright © 2008 Pearson Prentice Hall. All rights reserved. 1 Microsoft Office Excel Copyright © 2008 Pearson Prentice Hall. All rights reserved
Chapter 4: The Selection Process in Visual Basic.
Excel Introducing Excel Lesson 1. Manage Workbooks Excel is a spreadsheet program Excel is a spreadsheet program It organizes and analyzes data It organizes.
Visual Basic for Applications Macro Programming For Microsoft Office.
VBA Lab 2 I ns.Samia Al-blwi. Visual Basic Grammar Object: Visual Basic is an object-oriented language. This means that all the items in Excel are thought.
Chapter 1 Creating a Worksheet and a Chart
Week 4.  Recap – Ranges  For Each Loops  Ranges Referencing Range Objects  Set (keyword)
Lab 4 Range Review, Control Logic and Loops ► Range Review ► Control Logic and Loops ► Exercise.
Chapter 9 Macros And Visual Basic For Applications.
Visual Basic 2010 How to Program © by Pearson Education, Inc. All Rights Reserved.1.
Week 6.  Assessment 2  Do Loops  Custom Functions.
Visual Basic for Application - Microsoft Access 2003 Programming applications using Objects.
Introduction to Excel VBA UNC Charlotte CPE/PDH Series December 17, 2009.
The Excel model for information processing The Excel model is a grid of cells in which items of information are stored and processed. Any information that.
Visual Basic Objects / Properties / Methods PropertyAdjective ObjectNoun Part of the application Attribute MethodVerb Action to do something.
Controlling Program Flow with Looping Structures
Chapter 4 Decision Making. Agenda Function Goal Seek command AutoFilter command Worksheet operation Printing worksheet.
Microsoft Excel ( XP-2003). Return to Table of Contents Table of Contents 1_ Introduction to ExcelIntroduction to Excel 2_ Overview of the Excel.
Computer Literacy BASICS: A Comprehensive Guide to IC 3, 5 th Edition Lesson 18 Getting Started with Excel Essentials 1 Morrison / Wells / Ruffolo.
1 Lesson 18 Getting Started with Excel Essentials Computer Literacy BASICS: A Comprehensive Guide to IC 3, 4 th Edition Morrison / Wells.
Macros in Excel Using VBA Time Required – 5 hours.
Chapter 10 Using Macros, Controls and Visual Basic for Applications (VBA) with Excel Microsoft Excel 2013.
Chapter 6 Controlling Program Flow with Looping Structures.
COMPREHENSIVE Excel Tutorial 12 Expanding Excel with Visual Basic for Applications.
The Advantage Series ©2005 The McGraw-Hill Companies, Inc. All rights reserved Chapter 12 Introducing Visual Basic for Applications Microsoft Office Excel.
Excel Tutorial 8 Developing an Excel Application
GO! with Microsoft Office 2016
Exploring Excel Chapter 7 Automating Repetitive Tasks: Macros and
Formatting a Worksheet
Microsoft Office Illustrated
Learning Excel Session 9 and 10 Dr. Chaitali Basu Mukherji.
Microsoft Excel All editions of Microsoft office.
Exploring Microsoft Excel
Lesson 18 Getting Started with Excel Essentials
Introduction to computers
Microsoft Office Excel 2003
Spreadsheets and Data Management
Presentation transcript:

VBA Navigation, Conditionals, and Boxes

VBA Navigation

Background: Objects and Methods  Objects  Data-centric objects are structures that contain data and a set of predefined methods that manipulate the data. The following are examples of data-centric objects: a range of cells, an Excel worksheet, and a cell in a worksheet.  Tool-centric objects are tools with specific functionality that can be added to a workbook; e.g., button, form, textbox, etc.  Methods  Methods are a set of predefined actions that can be performed on the data contained in the object. Methods are tied directly to an object. They occur when an action takes place upon that object. They do not exist independent of that object.  A few of the many methods available for the Range object include the following: ClearContents, ClearFormats, Cut, Copy, Delete, Replace, and Select.

Background: Properties  Properties  Properties are characteristics of an object. In other words, a property is a piece of information that describes some aspect of an object (e.g., the value of a cell, the number of columns in a Range, the width of a column, etc.).  A few of the many properties available for the Range object include the following: Columns, Rows, ColumnWidth, Offset, Value, and VerticalAlignment.  In VBA code, methods and properties follow the object name. At first glance, this may seem backwards, but this sequence is common for object-oriented languages.

Within-Worksheet Navigation  Select method  Select method with Absolute References  Range(“ ”).Select To SelectExample A single cell Range("A3").Select A range of contiguous cells Range("B3:B6").Select Range("B3", "B6").Select Non-contiguous cells Range("A1,A5,B4").Select

Within-Worksheet Navigation  Select method  Select method with Relative References  [Origination Location].Offset(RowOffset,ColumnOffset)  RowOffset indicates the number of rows to move from the current location.  ColumnOffset indicates the number of columns to move from the current location.  Offset property requires an original location To MoveExample One cell down (e.g., from B2 to B3) Range("B2").Offset(1,0).Select One cell to the right (e.g., from B2 to C2) Range("B2").Offset(0,1).Select One cell up (e.g., from B2 to B1) Range("B2").Offset(-1,0).Select One cell to the left (e.g., from B2 to A2) Range("B2").Offset(0,-1).Select Five rows down and six columns right Range("A1").Offset(5,6).Select Origination PointExample Absolute reference Range("A1").Offset(2,3).Select Active cell Activecell.Offset(2,3).Select

Automatically finding the end of Ranges  It is often very useful to automatically find the end of a continuous data range. Consider the spreadsheet. The code must automatically determine how many employee records to process each pay period, since the number of employees is likely to change over time.  The code should begin at cell A3 and find the last non-blank value in column A. When using a computer keyboard, if you select cell A3 and then press CTRL+↓, the active cell will move to A6.

Automatically finding the end of Ranges  The table below shows keyboard shortcuts along with VBA equivalents for finding boundaries in a range  The following code begins at A3, finds, and returns the lowest non-empty row below the starting point. The number returned is 6.  lastrow = Range("A3").End(xlDown).Row Keystrok es VBA EquivalentWhat it Finds Ctrl+↓ Range.End(xlDown)Lowest non-blank row in range. Ctrl+↑ Range.End(xlUp)Highest non-blank row in range. Ctrl+→ Range.End(xlToRight)Right-most non-blank column in the range. Ctrl+← Range.End(xlToLeft)Left-most non-blank column in the range

Using the Application Command to enable use of Worksheet functions  The Application key word allows VBA to apply an Excel worksheet function right in the VBA code.  This will calculate the sum of the cells in the range from B3 to the lowest contiguous value below cell B3 (B6 in this case). The portion of the code on the right selects the entire range. The code on the left side invokes the worksheet function to process the contents of the range.  Sum1 = Application.Sum(Range("B3", Range("B3").End(xlDown)))  This finds the average of the same range of cells.  Avg1 = Application.Average(Range("B3", Range("B3").End(xlDown)))

Referencing Non-Selected Cells  In this example spreadsheet, the Tax Amount and Net Pay are to be calculated for each employee:  The Offset parameter can be used to get data from a non-selected cell or to write data to non-selected cell. In other words, one location can be selected and Offset can be used to do work on cells that are nearby but that are not selected.

Referencing Non-Selected Cells 01 Sub NetPay() Dim GrossPay As Currency, TaxRate As Currency 04 Dim TaxAmount As Currency, NetPay As Currency 05 Range("A3").Select 06 GrossPay = ActiveCell.Offset(0, 1).Value‘the Offset parameter is used with Value parameter to get values out of non- ‘selected cells 07 TaxRate = ActiveCell.Offset(0, 2).Value 08 TaxAmount = GrossPay * TaxRate 09 NetPay = GrossPay - TaxAmount 10 ActiveCell.Offset(0, 3).Value = TaxAmount‘the Offset parameter is also used with the Value parameter to ‘write values into non-selected cells 11 ActiveCell.Offset(0, 4).Value = NetPay 12 ActiveCell.Offset(1, 0).Select ‘Select moves to the next record End Sub

Referencing Non-Selected Cells 01 Sub NetPay() Dim GrossPay As Currency, TaxRate As Currency 04 Dim TaxAmount As Currency, NetPay As Currency 05 Range("A3").Select 06 Do Until IsEmpty(Selection.Value)‘Loop repeats until cell value is empty 07 GrossPay = ActiveCell.Offset(0, 1).Value 08 TaxRate = ActiveCell.Offset(0, 2).Value 09 TaxAmount = GrossPay * TaxRate 10 NetPay = GrossPay - TaxAmount 11 ActiveCell.Offset(0, 3).Value = TaxAmount 12 ActiveCell.Offset(0, 4).Value = NetPay 13 ActiveCell.Offset(1, 0).Select 14 Loop End Sub

Navigation between tabs within the same Workbook  The names on the left (e.g., Sheet1, Sheet2) are the default names assigned by Excel. The names on the right, e.g., (Output), (Input), are the names assigned by the user when the user decided to change the name of the tab to something other than the default name:  The Sheets command uses the user-assigned name. That is, the name on the right. The Sheets command lets you move among different worksheets (tabs) within the same workbook. It takes a single argument: the name of the sheet that you would like to select.  The following selects the worksheet named "Input". The next line selects cell A2 on that worksheet.  Sheets("Input").Select  Range("A2").Select

VBA Conditionals

If-Then-Else FlowchartVBA Code If-Then-Null-ElseIf MS > SG Then B = BP * MS End If If-Then-ElseIf ET = True Then GP = H * R Else GP = SA End If

Select Case Select Case test_variable Case condition_1 Code to run if condition_1 Case condition_n Code to run if condition_n Case Else Code to run if Else End Select

Select Case / If...Else If Select...Case Select Case LRegion Case "N" LRegionName = "North" Case "S" LRegionName = "South" Case "E" LRegionName = "East" Case Else LRegionName = "West" End Select If LRegion = "N" Then LRegionName = "North" ElseIf LRegion = "S" Then LRegionName = "South" ElseIf LRegion = "E" Then LRegionName = "East" Else 'Legion = "W" LRegionName = "West" End If

Select Case / If...Else If Select...Case using “To” keyword Select Case LNumber Case 1 To 10 LRegionName = "North" Case 11 To 20 LRegionName = "South" Case 21 To 30 LRegionName = "East" Case Else LRegionName = "West" End Select LNumber = 30 If LNum >= 1 And LNumber <= 10 Then LRegionName = "North" ElseIf LNum >= 11 And LNumber <= 20 Then LRegionName = "South" ElseIf LNum >= 21 And LNumber <= 30 Then LRegionName = "East" Else LRegionName = "West" End If

Select Case / If...Else If Select…Case Enumerating with commas Select Case LNum Case 1, 2 LRegionName = "North" Case 3, 4 LRegionName = "South" Case 5, 6 LRegionName = "East" Case 7, 8 LRegionName = "West" End Select f LNum = 1 Or LNum = 2 Then LRegionName = "North" ElseIf LNum = 3 Or LNum = 4 Then LRegionName = "South" ElseIf LNum = 5 Or LNum = 6 Then LRegionName = "East" Else LRegionName = "West" End If

Boxes

Input Box  An Input Box function displays an input box on top of the excel workbook, which allows the user to type a value into a dialog box. The content typed by the user into the input box is stored as string variable that will be remembered for later use in a procedure.  Variable = InputBox (Prompt, [Title])

Input Box 01 Sub Try() 02 Dim Ans As String 03 Ans = InputBox("Want milk (y/n)?", "Enter Data") 04 If Ans = Empty Then Exit Sub 05 If Ans = "y" Then 06 MsgBox "I'll get you a glass." 07 ElseIf Ans = "n" Then 08 MsgBox "I'll put the milk away." 09 Else 10 MsgBox "Unexpected input. Exiting…” 11 End If 12 End Sub

MsgBox  The VBA MsgBox function displays a message in a window on the computer screen over the top of the worksheet and waits for the user to click on a button. No additional lines of code execute until the user presses the OK button on the screen.  In concatenating text, the “&” operator is used to join strings. Sub getMonths() Dim Yrs As Integer, Mnths As Integer Yrs = 10 Mnths = Yrs * 12 MsgBox "You are " & Mnths & " months old." End Sub