Excel VBA Programming For Dummies. Dick Kusleika
Чтение книги онлайн.

Читать онлайн книгу Excel VBA Programming For Dummies - Dick Kusleika страница 19

Название: Excel VBA Programming For Dummies

Автор: Dick Kusleika

Издательство: John Wiley & Sons Limited

Жанр: Программы

Серия:

isbn: 9781119843092

isbn:

СКАЧАТЬ alt="Technicalstuff"/> PAUSE FOR A TERMINOLOGY BREAK

      Throughout this book, you’ll see the terms Sub procedure, routine, program, procedure, and macro. These terms can be a bit confusing. Programming folks usually use the word procedure to describe an automated task. Technically, a procedure can be a Sub procedure or a Function procedure — both of which are sometimes called routines — or even programs. All these terms can be used interchangeably. As detailed in later chapters, however, an important distinction exists between Sub and Function procedures. For now, don’t worry about the programming terminology. Just try to understand the concepts.

      

A single line of VBA code can be as long as you need it to be. However, you might want to use the line-continuation characters to break up lengthy lines of code. To continue a single line of code (also known as a statement) from one line to the next, end the first line with a space followed by an underscore (_). Then continue the statement on the next line. And don’t forget the space. An underscore character that’s not preceded by a space won’t do the job.

      Here’s an example of a single statement split into three lines:

       Selection.Sort Key1:=Range("A1"), _ Order1:=xlAscending, Header:=xlGuess, _ Orientation:=xlTopToBottom

      This statement would perform exactly the same way if it were entered in a single line (with no line-continuation characters). Notice that the second and third lines of this statement are indented. Indenting is optional, but it helps you see that these lines are not separate statements.

      

The white-coated engineers who designed the VBE anticipated that people like us would make mistakes. Therefore, the VBE has multiple levels of undo and redo buttons. If you deleted a statement that you shouldn’t have, click the Undo button on the toolbar (or press Ctrl+Z) until the statement shows up again. After undoing, you can click the Redo button to perform the changes you’ve undone. Are you ready to enter some real-live code? Try the following steps:

      1 Create a new workbook in Excel.

      2 Press Alt+F11 to activate the VBE.

      3 Click the new workbook’s name in the Project Explorer.

      4 Choose Insert ⇒ Module to insert a VBA module into the project.

      5 Type the following code in the module: Sub GuessName() Msg = "Is your name " & Application.UserName & "?" Ans = MsgBox(Msg, vbYesNo) If Ans = vbNo Then MsgBox "Oh, never mind." If Ans = vbYes Then MsgBox "I must be psychic!"End Sub

      6 Position the cursor anywhere within the text you typed and press F5 to execute the procedure.F5 is a shortcut for Run ⇒ Run Sub/UserForm. If you entered the code correctly, Excel executes the procedure, and you can respond to the simple dialog box shown in Figure 3-4. The text in the dialog box that appears on your screen will differ, of course, from the text shown in the figure.

Snapshot of GuessName procedure displays this dialog box.

      FIGURE 3-4: The GuessName procedure displays this dialog box.

      When you enter the code listed in Step 5, you might notice that the VBE makes some adjustments to the text you enter. For example, after you type the Sub statement, the VBE automatically inserts the End Sub statement. And if you omit the space before or after an equal sign, the VBE inserts the space for you. Also, the VBE changes the color and capitalization of some text. This is all perfectly normal. It’s just the VBE’s way of keeping things neat and readable.

      COMPILE ERROR?

      There’s a chance that the GuessName macro won’t work. When you try to run it, Excel may complain and pop up an error message: Compile Error: Variable Not Defined. Don’t worry; there’s an easy fix for that.

      If you receive that error, look at the top of your module, and you’ll see this text: Option Explicit. Just delete that line, and the macro should work. That line, when present at the top of a module, means that you must “declare” all your variables. (See Chapter 7 for more about variables.) If that line was added, it means that your VBE is set up to add the line automatically. For now, don’t worry about it. Delete the line, and forget about the rude interruption.

      For the record, the following concepts were used to create this simple macro, all of which are covered later in this book:

       Defining a Sub procedure (the first line)

       Assigning values to variables (Msg and Ans)

       Concatenating (joining) a string (using the & operator)

       Using a built-in VBA function (MsgBox)

       Using built-in VBA constants (vbYesNo, vbNo, and vbYes)

       Using an If-Then construct (twice)

       Ending a Sub procedure (the last line)

      Not bad for a beginner, eh?

      Using the macro recorder

      Another way you can get code into a VBA module is by recording your actions, using the Excel macro recorder. If you worked through the hands-on exercise in Chapter 2, you already have some experience with this technique.

      

By the way, there is absolutely no way you can record the GuessName procedure shown in the preceding section. You can record only things that you can do directly in Excel. Displaying a message box is not in Excel’s normal repertoire. (It’s a VBA thing.) The macro recorder is useful, but in many cases, you’ll probably need to enter at least some code manually.

      Here’s a step-by-step example that shows how to record a macro that inserts a new worksheet and hides all but the first 10 rows and all but the first 10 columns. If you want to try this example, follow these steps:

      1 Open a new, blank workbook.

      2 Click the Developer tab, and make sure that Use Relative References is not highlighted.This macro is recorded using Absolute References.

      3 Choose Developer ⇒ Code ⇒ Record СКАЧАТЬ