Using Loops to Repeat Code



Similar documents
Introducing VBA Message Boxes

Visual Basic: Objects and collections

Connecting to an Excel Workbook with ADO

The following tips have been copied from the following website:

1. a procedure that you perform frequently. 2. Create a command. 3. Create a new. 4. Create custom for Excel.

Microsoft Excel 2013 Step-by-Step Exercises: PivotTables and PivotCharts: Exercise 1

Working with Macros and VBA in Excel 2007

A Comparison of SAS versus Microsoft Excel and Access s Inbuilt VBA Functionality Jozef Tarrant, Amadeus Software Ltd., Oxford, UK

How To Code In Vba Vb.Io (For Ahem)

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

RIT Installation Instructions

Introduction. Syntax Statements. Colon : Line Continuation _ Conditions. If Then Else End If 1. block form syntax 2. One-Line syntax. Do...

Financial Data Access with SQL, Excel & VBA

Creating Applications using Excel Macros/Visual Basic for Applications (VBA)

Construction Administrators Work Smart with Excel Programming and Functions. OTEC 2014 Session 78 Robert Henry

Fig. 1 Visit the Add-Ins dialog to view and load available Add-Ins.

Excel Reporting with 1010data

Add an Audit Trail to your Access Database

3 IN THIS CHAPTER. Referring to Ranges. The Range Object The following is the Excel object hierarchy:

Excel & Visual Basic for Applications (VBA)

Fig. 1 Suitable data for a Crosstab Query.

P R E M I E R. Microsoft Excel 2007 VBA (Macros) Premier Training Limited 4 Ravey Street London EC2A 4QP Telephone +44 (0)

Writing Macros in Microsoft Excel 2003

Creating Basic Excel Formulas

Fig. 1 The finished UserForm project.

Visual Basic - Modules and Procedures

Final Exam Review: VBA

Programming MS Excel in Visual Basic (VBA)

Module 2 - Multiplication Table - Part 1-1

USING EXCEL 2010 TO SOLVE LINEAR PROGRAMMING PROBLEMS MTH 125 Chapter 4

ESCI 386 IDL Programming for Advanced Earth Science Applications Lesson 6 Program Control

Hands-on Exercise 1: VBA Coding Basics

In This Issue: Excel Sorting with Text and Numbers

Like any function, the UDF can be as simple or as complex as you want. Let's start with an easy one...

Changing the Display Frequency During Scanning Within an ImageControls 3 Application

Macros allow you to integrate existing Excel reports with a new information system

Finding the last cell in an Excel range Using built in Excel functions to locate the last cell containing data in a range of cells.

Programming in Access VBA

EXAMPLE WITH NO NAME EXAMPLE WITH A NAME

MICROSOFT EXCEL FORMULAS

Moving from C++ to VBA

Microsoft Excel 2013: Macro to apply Custom Margins, Titles, Gridlines, Autofit Width & Add Macro to Quick Access Toolbar & How to Delete a Macro.

2. The Open dialog box appears and you select Text Files (*.prn,*.txt,*.csv) from the drop-down list in the lower right-hand corner.

SPV Reporting Tool VBA Code User Guide. Last Updated: December, 2009

Automation of 1DCutX in Excel by VBA.

Word 2010: Mail Merge to with Attachments

Commonly Used Excel Formulas

THE HELLO WORLD PROJECT

Python Lists and Loops

ACS Microcomputer Workshop Excel: Functions and Data Analysis Tools

Getting Started. Tutorial RIT API

Unleashing Hidden Powers of Inventor with the API Part 2 of 4: Using iproperties with Inventor VBA

CHAPTER 11: STATEMENTS OF CASH FLOW

Program to solve first and second degree equations

A Concise Guide for Beginners LIEW VOON KIONG

How to download historical data for a list of securities from outside of Bloomberg using Bloomberg Excel API s History Wizard

USC Marshall School of Business Marshall Information Services

ABN Lookup tool. Version 9.0

Excel s Business Tools: What-If Analysis

Introduction to Microsoft Access 2003

How to write and track Additional Requests using Excel/Word

Excel 2013 Sort: Custom Sorts, Sort Levels, Changing Level & Sorting by Colored Cells

Performing Simple Calculations Using the Status Bar

Training Needs Analysis

MICROSOFT ACCESS STEP BY STEP GUIDE

VB.NET Programming Fundamentals

Departmental Reporting in Microsoft Excel for Sage 50 Accounts

What is a Loop? Pretest Loops in C++ Types of Loop Testing. Count-controlled loops. Loops can be...

Migrating to Excel 2010 from Excel Excel - Microsoft Office 1 of 1

6. Control Structures

Systems Programming & Scripting

Sample Table. Columns. Column 1 Column 2 Column 3 Row 1 Cell 1 Cell 2 Cell 3 Row 2 Cell 4 Cell 5 Cell 6 Row 3 Cell 7 Cell 8 Cell 9.

Commonly Used Excel Functions. Supplement to Excel for Budget Analysts

SOME EXCEL FORMULAS AND FUNCTIONS

Formulas & Functions in Microsoft Excel

Highline Excel 2016 Class 26: Macro Recorder

PULSE Automation programming in Visual Basic. From BK training lectures arranged by Jiří Tůma & Radovan Zadražil

Using Casio Graphics Calculators

Microsoft Excel 2010 Part 3: Advanced Excel

MICROSOFT EXCEL Formulas, Functions, & Macros. Documented by Vincent J. Yanusauskas Computer Training Coordinator

Excel Pivot Tables. Blue Pecan Computer Training Ltd - Onsite Training Provider :: :: info@bluepecan.co.

Excel Project From the Start menu select New Office Document. If necessary, click the General tab and then double-click Blank workbook.

Sample- for evaluation only. Advanced Excel. TeachUcomp, Inc. A Presentation of TeachUcomp Incorporated. Copyright TeachUcomp, Inc.

To add a data form to excel - you need to have the insert form table active - to make it active and add it to excel do the following:

A Microsoft Access Based System, Using SAS as a Background Number Cruncher David Kiasi, Applications Alternatives, Upper Marlboro, MD

Microsoft Excel 2007 Mini Skills Overview of Tables

EXCEL VBA ( MACRO PROGRAMMING ) LEVEL SEPTEMBER AM-5.00PM MENARA PJ@AMCORP PETALING JAYA

Microsoft Access 2010

Chapter 3. Cartesian Products and Relations. 3.1 Cartesian Products

Using GABRIEL Excel to XML Templates

Centre for Staff & Educational Development (CSED) Discover your potential. Excel. Introduction to VBA

Perl in a nutshell. First CGI Script and Perl. Creating a Link to a Script. print Function. Parsing Data 4/27/2009. First CGI Script and Perl

Q&As: Microsoft Excel 2013: Chapter 2

Excel & Visual Basic for Applications (VBA)

MS Excel. Handout: Level 2. elearning Department. Copyright 2016 CMS e-learning Department. All Rights Reserved. Page 1 of 11

EXCEL 2007 VLOOKUP FOR BUDGET EXAMPLE

Page 1 EXPERT. 1.1 Manage Multiple Workbooks Pages Where Covered Modifying existing templates. 356 (Step 7 Tip) Merging multiple workbooks

Lesson 4.3: Using the VLOOKUP Function

Exercise 1: Python Language Basics

Using Excel and VBA CHANDAN SENGUPTA SECOND EDITION. WILEY John Wiley & Sons, Inc.

Transcription:

Using s to Repeat Code Why You Need s The macro recording tools in Microsoft Word and Microsoft Excel make easy work of creating simple coding tasks, but running a recorded macro is just that you do a job once. If you need to do the job again on another document, paragraph or worksheet you have to run the macro again. To do that automatically you need a code loop. A loop is created by a set of code statements that cause a piece of code to be repeated over and over again, as many times as necessary. There are different kinds of loop to suit different situations. The code required is usually quite simple and, once mastered, will help you unleash the true power of VBA. The examples shown here use Microsoft Excel, although the techniques are the same for any program that supports VBA. ing through a Collection (For Each Next) A program's object model contains a number of collections of objects. The Excel Application object contains a collection of workbooks. The Workbook object contains a collection of worksheets. The Worksheet object contains collections of cells, columns, rows etc. VBA uses a For Each Next loop to iterate through each member of a collection. The code starts by declaring a variable which represents the object you want to examine (i.e. the member of the collection). This example (Listing 1) loops through the worksheets in a workbook to determine if one with a particular name already exists. If not, it creates one with that name. Listing 1 Sub AddSheet_1() If objsheet.name = "NewSheet" Then Exit Sub The statement For Each instructs the program that you wish the code to repeat as many times as there are objects in the collection (unless you subsequently tell it otherwise). When the statement Next is reached the macro is sent back to the beginning of the loop until the job is done. The code inside the loop includes a simple If Statement that terminates the macro with the command Exit Sub if a sheet with the specified name is found. There is no point in continuing the loop to look at any remaining sheets if the one being sought has already been found. If the named worksheet is not found the loop will run its course and move on to the next part of the macro which adds then names a new worksheet. You could include a slightly more elaborate If Statement. Here (Listing 2) a message is displayed if the named sheet is found, and the sheet activated (i.e. selected) before the macro exits: Listing 2 Sub AddSheet_2() If objsheet.name = "NewSheet" Then MsgBox "A worksheet with that name already exists." Worksheets("NewSheet").Activate Exit Sub Martin Green www.fontstuff.com 1

The next example (Listing 3) loops through a collection of cells looking for a cell containing a particular value (in this case today's date). If it finds one it displays a message the selects the cell and cancels the macro. Listing 3 Sub FindCell_1 () Dim objcell As Object For Each objcell In ActiveSheet.UsedRange.Cells If objcell.value = Date Then objcell.select MsgBox "Today's date was found in cell: " & objcell.address Exit Sub Next objcell MsgBox "No cell containing today's date was found." The code specifies the UsedRange of the active sheet as the area to search. There are many different ways to specify the range. For example, You could specify a particular range: For Each objcell In ActiveSheet.Range("A1:C25").Cells You might want the macro to work on a certain column (here the second column, column "B"): For Each objcell In ActiveSheet.Columns(2).Cells Or you might prefer to select a block of cells and work on the selection: For Each objcell In Selection.Cells Continuing the In each of the examples shown above the macro was terminated when the object was found. If you want the loop to continue and examine all the members of the collection, simply omit the Exit Sub statement. Remember that doing this might have an implication on the code that comes after the loop. For example, the code in Listing 3 stops after finding just the first cell containing today's date. The date might occur in several cells. The next example (Listing 4) keeps a note of each relevant cell's address by adding it to a string variable (preceded by a comma). Then, when the loop finishes, if the variable is empty (i.e. its length is zero) this shows that no cells were noted, but if cells were found a statement removes the leading comma from the string then uses it to specify a range of cells to be selected. Listing 4 Sub FindCell_2() Dim objcell As Object Dim strrange As String For Each objcell In ActiveSheet.UsedRange.Cells If objcell.value = Date Then strrange = strrange & "," & objcell.address Next objcell If Len(strRange) = 0 Then MsgBox "No cell containing today's date was found." strrange = Right(strRange, Len(strRange) - 1) Range(strRange).Select MsgBox "Today's date appears in the selected cells" Exiting the but Continuing the Macro If you want your macro to continue after the loop, but you want to save time by having the code terminate the loop when the required object is found, you can do this without having to exit the macro by using the statement Exit For instead of Exit Sub. The command Exit For causes the macro to jump to the first line following the Next statement. Martin Green www.fontstuff.com 2

Listing 5 Sub AddSheet_3() Dim blnfound As Boolean If objsheet.name = "NewSheet" Then blnfound = True Exit For If Not blnfound Then MsgBox "This workbook contains " & Worksheets.Count & " sheets." The macro in Listing 5 uses the Exit For statement to terminate the loop if a suitable sheet is found but also notes this by setting the value of the boolean (True/False) variable to True. When the loop terminates, either because it ran its course or because a sheet was found, an If Statement checks the value of the variable and only creates a new sheet if the value is not False. The macro then continues in this example displaying a message showing the number of sheets in the workbook. ing for Number of Times (For Next) If you know, or can find out, how many times you want a loop to run then you can use a For Next loop. You might use this kind of loop to move down a column of cells performing a particular task. The number of times the loop runs is specified using a start number (usually 1 or 0) and finish number. A counter variable (here named "i") keeps count of the loop's progress. The finish number can be hard-coded, for example: For i = 1 To 25 Or, more usually, calculated or determined in some way and sometimes specified as a variable: For i = 1 To Selection.Rows.Count These examples look at the cells in column "A" and write a value in column "B". Their task is to determine whether the value in column "A" is odd or even. They do this by halving it and testing if the result is a whole number by comparing it with the integer of the same calculation. If it is so, the original value must be an even one. They determine how many times to run the loop by counting the number of rows in the CurrentRegion of cell "A1" (i.e. the area adjacent to that cell containing values). The first example (Listing 6) selects each cell as it moves down the column, referring to the selected cell as the ActiveCell. Listing 6 Sub OddOrEven_1() Dim introwcount As Integer introwcount = Range("A1").CurrentRegion.Rows.Count For i = 1 To introwcount If ActiveCell.Value / 2 = Int(ActiveCell.Value / 2) Then ActiveCell.Offset(0, 1).Value = "Even" ActiveCell.Offset(0, 1).Value = "Odd" Next i Although perfectly serviceable, this syntax is inefficient and slow because each cell has to be selected. A more efficient way is to refer to the cell in question using the Offset property of the starting cell as shown in the next example (Listing 7). The Row component of the Offset property is supplied by the value of the counter "i": Martin Green www.fontstuff.com 3

Listing 7 Sub OddOrEven_2() Dim introwcount As Integer introwcount = Range("A1").CurrentRegion.Rows.Count For i = 0 To introwcount - 1 If Range("A1").Offset(i, 0).Value / 2 = _ Int(Range("A1").Offset(i, 0).Value / 2) Then Range("A1").Offset(i, 1).Value = "Even" Range("A1").Offset(i, 1).Value = "Odd" Next i In addition to specifying the start and finish values of the counter variable you can declare a Step value if, for example you want your loop to proceed in units of more than one: For i = 1 To 100 Step 2 Your loop can run in reverse order if the start an finish numbers are reversed. If you do this you must also declare a negative step value: For i = 100 To 1 Step -1 ing Until a Certain Condition is Satisfied ( Until) This method can be useful if you are unable to ascertain how many times to run the loop. It terminates the loop when a certain condition is satisfied. The first example (Listing 8) finds the location of the first empty cell in a column. It starts by selecting the first cell (in this case "A1") then selects the cell below and checks whether or not it is empty. If the selected cell empty the loop automatically terminates and leaves the empty cell selected. Listing 8 Sub FindEmptyCell_1() Until IsEmpty(ActiveCell.Value) The syntax can be expressed as: Until <Condition> which does not apply the test to the start cell, or: Until <Condition> which does apply the test to the start cell. As mentioned earlier, selecting cells in a code loop is an inefficient way of working and could be slow if a lot of rows are to be processed. The next example (Listing 9) uses the loop to increase the value of a counter variable ("i") by one, then uses the final value of "i" to determine which cell gets selected when the loop finishes: Listing 9 Sub FindEmptyCell_2() i = i + 1 Until IsEmpty(Range("A1").Offset(i, 0).Value) Range("A1").Offset(i, 0).Select Martin Green www.fontstuff.com 4

Exiting the As with a For Next loop you can have your code terminate a loop by using the statement Exit. ing Whilst a Certain Condition is Satisfied ( While ) This is very similar to the last kind of loop. It causes the loop to run s long as a particular condition is satisfied and uses the syntax: While <Condition> Or: While <Condition> This example (Listing 10) simply uses the opposite of the condition used in Listing 8. Listing 10 Sub FindEmptyCell_3() While Not IsEmpty(ActiveCell.Value) These examples have all been used to look for an empty cell, but your condition can be any expression that can be evaluated and expressed. Your loop might be working down an ascending column of dates, either hard-coding a condition: While ActiveCell.Value < #01/07/2007# or calculating it: While ActiveCell.Value < DateAdd("m", 6, Date) Alternative Syntax You might see code using the syntax While Wend. Although this syntax is supported by VBA it is not commonly used today, being a remnant of older Basic code. Here is an example (Listing 11). Listing 11 Sub FindEmptyCell_4() While IsEmpty(ActiveCell.Value) = False Wend Martin Green www.fontstuff.com 5