0% found this document useful (0 votes)
71 views

The Macro Code

This document provides examples of different types of macros in Visual Basic for Applications (VBA) for Excel, including how to write macros using Do...Loop, For Each...Next Loop, and nested loop structures. It explains what each macro does and includes the VBA code for common tasks like combining columns, formatting cells based on their contents, and deleting duplicate rows.

Uploaded by

viktóriam_6
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
71 views

The Macro Code

This document provides examples of different types of macros in Visual Basic for Applications (VBA) for Excel, including how to write macros using Do...Loop, For Each...Next Loop, and nested loop structures. It explains what each macro does and includes the VBA code for common tasks like combining columns, formatting cells based on their contents, and deleting duplicate rows.

Uploaded by

viktóriam_6
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 9

The macro code language for most Office programs, including Excel, is Visual Basic for Applications (VBA).

You may have recorded macros in Excel by stepping through actions that the program saves for you. When you record a macro, Excel records the VBA code describing your actions in a module attached to the workbook. Think of a module as a container for a number of macros. Would that be easier to remember as a list of definitions?

macro: a bit of code that produces a specific effect and has its own name VBA: Visual Basic for Applications, the code language of macros module: a container for storing macros, attached to a workbook

Suppose you wanted to write a macro. First things first: You'd need to open the Visual Basic Editor. On the Tools menu, you'd point to Macro, and then you'd click Visual Basic Editor. Why would this be the first thing you'd do? Because the Visual Basic Editor is a tool for writing and editing VBA. The name kind of gives that away.
Second things second: Before you started writing a macro, you'd need to decide where to keep it. Remember modules? Modules are containers for macros, attached to a workbook through a larger container called a VBA Project. You'd add a new module in the Visual Basic Editor by selecting Module on that editor'sInsert menu (not the spreadsheet's menu). A blank module window would then appear inside the main window of the Visual Basic Editor.

To actually write a macro, you'd type the word Sub in the module window. (Why? It doesn't matter. It's just that way.) Next you'd type a space and then the name of your macro. If you typed Sub MyMacro, for instance, you'd create a new macro called MyMacro. Because the Visual Basic Editor is so smart, it would automatically insert a line below your Sub line that said End Sub how convenient! You've got the beginning and the end, now all you need is some code between them, in the handy new space.

Suppose you'd followed these steps and created a macro. Because there's nothing between your Sub line and your End Sub line, your new macro wouldn't actually do anything. You'd need to add code to bring your macro alive. Here's an example. Say you wanted to show a simple message. Between the Sub line and the End Sub lines, you would type:

While MsgBox may look like a typo, this is the VBA word for a message box. Because VBA is very literal, you must type exactly what appears above, and it's important to include the quotation marks around the rest of the text in this line of code. If you ran this macro, Excel would show a message containing My first macro and an OK button, which would close the message. In the practice that's coming up next, you'll get a chance to write and run this macro. Tip A great way to create your own code example is to record a macro for the action first. On the Tools menu, point

to Macro and select Record New Macro. Once you've recorded the macro, take a look at it in the Visual Basic Editor to see how its code works. On the Tools menu, point to Macro and then selectMacros to find the one you recorded. Select it and click Edit to see the code.

A DoLoop counts rows in a range of data as long as it does not find a blank row.

Suppose you wanted to count the number of rows in a range of data that can sometimes be small and sometimes really big. You'd want to use a DoLoop. This type of loop performs an action as many times as necessary. It would count whatever number of rows it found in the range. Or suppose you wanted to perform one action on two ranges of data containing different numbers of rows. Again, you'd use a DoLoop. The loop would run as many times as necessary for each of the two ranges. How does the loop know what's necessary? You tell it. The loop stops running when it meets a specific piece of data, such as a blank line or some particular text. You use either the While condition or the Until condition to specify when aDoLoop will stop. As long as something is true, or until something is true, the loop runs. So for a loop that stops when it finds a blank cell in the first column, you would use the While condition, as follows:

Here the While condition is used so that the loop runs as long as the cell being acted on is not blank. The row being worked on is x, and (x,1) is the first cell in that row. Used together, the signs <> mean "does not equal." The quotation marks with nothing between them indicate a blank cell. If you wanted the loop to run until it found a cell containing the number 365, you'd use the Until condition. Either way, you tell the loop how to know when it's time to stop.

A For EachNext Loop makes the word "OK" darker than other text, everywhere in a selection.

You would use the For EachNext loop to perform an action on every cell in a range of data. Suppose, for example, that you wanted to make the word "OK" darker than other text everywhere in a selected range. Your code would look like this:

"MyCell" means whatever cell the loop is working on, and "For Each" means that the loop will work on all cells in the selection. If the loop finds a cell containing only the word "OK", then it makes that word darker. (The appearance of text is controlled by the Font property, and the Bold property means darker text.)

Columns represented as numbers instead of letters.

Loop macros use two different methods to bring a cell's data into their code. One is called the Cells property, and the other is called the Range property. In VBA, it is usually easier and more convenient to use the Cells property, because it is easier to change the values described by that property. The Range property identifies rows and columns using the worksheet numbers and letters, while theCells property uses numbers for both rows and columns. Adding +1 to those numbers moves a loop macro conveniently from row to row and from column to column, but there is no convenient way to move from one letter to the next in the code. Tip You can see column numbers instead of column letters in your spreadsheet if you prefer. On the Tools menu, click Options, and then select theGeneral tab. Check the "R1C1 reference style" box. If you want to change again later, clear that check box.

This DoLoop macro combines two columns into a third.

With this macro, you could combine values from two columns into a third column, with a space between them. In the practice data, the columns to combine are First Name, Last Name, and Full Name, as shown in the illustration. You might be thinking "I could do this with a formula is a

macro really necessary?" And you would be right. You can do many things in Excel with formulas, and this process happens to be a prime candidate for a formula. However, this example also makes clear just how a DoLoop works and what you can accomplish with this type of loop.

In this example, the first name and last name are copied into the Full Name column with a space between them. This operation is performed while the value of Cells(x,3) is not blank. The variable x is used to track the current row number, and increasing x moves the operation to the next row. The columns are specified by the nonvariable values of 3, 4, and 5, which represent columns C, D, and E, respectively. Tip Pay careful attention to the comment text in green when you are trying to understand these VBA macros. When you are working in the Visual Basic Editor, you can insert more comments by typing an apostrophe at the beginning of a new line. VBA will ignore that line when it runs the macro.

This For EachNext Loop macro reads each cell and colors it according to the contents.

With this macro, you could set the background colors of cells in a selected range. The background will be red if a cell has the word "book" in it, green if it has the word "movie" in it, blue if it contains any other value, and clear if the cell is blank. This process could be accomplished by using the Conditional Formatting feature. However, this code example shows how to operate on all cells in a selected range with a loop.

"MyCell" is a variable that tracks the cell the loop is acting on. The asterisks in the code example allow the code to find the specified text when it is part of more text. As you see in the illustration, this code does not search only for text starting with capital letters. It finds both "Book" and "Read the book." To obtain this behavior, you would need to specify it before entering the macro. At the very beginning of the module, before typing Sub or pasting any other code, you would enter the following code:

This option specifies that any following code using the Like operator will ignore the case of text it acts on. Without this option, the code example would change background color only when it found text starting with a capital letter.

This nested loop macro deletes rows with duplicate values in two columns.

With this macro, you could delete rows that contain duplicate values in columns D and F both. The power of this macro is that you can adapt it to act on duplicate values in other columns in your data. Note Take care when running this macro! It will delete data from your spreadsheet. And when you run a macro, there is no Undo. What's done is done. To be safe, copy your data first, and run this macro on the copy to test the results.

The inside loop finds any rows that duplicate the starting row, and removes them. The outside loop moves the starting row down the selection, one row at a time, until each row has been compared with all those below it in the selection.

You might also like