Dick Kusleika - Excel VBA Programming For Dummies

Здесь есть возможность читать онлайн «Dick Kusleika - Excel VBA Programming For Dummies» — ознакомительный отрывок электронной книги совершенно бесплатно, а после прочтения отрывка купить полную версию. В некоторых случаях можно слушать аудио, скачать через торрент в формате fb2 и присутствует краткое содержание. Жанр: unrecognised, на английском языке. Описание произведения, (предисловие) а так же отзывы посетителей доступны на портале библиотеки ЛибКат.

Excel VBA Programming For Dummies: краткое содержание, описание и аннотация

Предлагаем к чтению аннотацию, описание, краткое содержание или предисловие (зависит от того, что написал сам автор книги «Excel VBA Programming For Dummies»). Если вы не нашли необходимую информацию о книге — напишите в комментариях, мы постараемся отыскать её.

Find out what Excel is capable of with this step-by-step guide to VBA
Excel VBA Programming For Dummies
Excel VBA, Excel VBA Programming For Dummies

Excel VBA Programming For Dummies — читать онлайн ознакомительный отрывок

Ниже представлен текст книги, разбитый по страницам. Система сохранения места последней прочитанной страницы, позволяет с удобством читать онлайн бесплатно книгу «Excel VBA Programming For Dummies», без необходимости каждый раз заново искать на чём Вы остановились. Поставьте закладку, и сможете в любой момент перейти на страницу, на которой закончили чтение.

Тёмная тема
Сбросить

Интервал:

Закладка:

Сделать

In general, a VBA module can hold three types of code:

Declarations: One or more information statements that you provide to VBA. For example, you can declare the data type for variables you plan to use or set some other module-wide options. Declarations are basically housekeeping statements. They aren’t actually executed.

Sub procedures: A set of programming instructions that, when executed, performs some action.

Function procedures: A set of programming instructions that returns a single value (similar in concept to a worksheet function, such as SUM).

A single VBA module can store any number of Sub procedures, Function procedures, and declarations. Well, there is a limit — about 64,000 characters per module. It’s unlikely you’ll even get close to reaching the 64,000-character limit. But if you did, the solution is simple: Just insert a new module.

How you organize a VBA module is completely up to you. Some people prefer to keep all their VBA code for an application in a single VBA module; others like to split the code into several modules. The best practice is to store related procedures in their own modules. For example, you might keep all the procedures that deal with importing and exporting data in a module called ImportExport, all the procedures that deal with formatting cells in a module called Formatting, and all the procedures that deal with printing in a module called Printing. Organizing your code in this manner makes it easier for you and others to understand and, if necessary, modify the code.

Getting VBA code into a module

An empty VBA module is like the fake food you see in the windows of some restaurants; it looks good, but it doesn’t really do much for you. Before you can do anything meaningful, you must have some VBA code in the VBA module. You can get VBA code into a VBA module in three ways:

Enter the code directly.

Use the Excel macro recorder to record your actions and convert those actions to VBA code (see Chapter 6).

Copy the code from one module and paste it into another.

Entering code directly

Sometimes, the best route is the most direct one. Entering code directly involves … well, typing the code using your keyboard. Entering and editing text in a VBA module works as you might expect. You can select, copy, cut, paste, and drag-and-drop.

Excel VBA Programming For Dummies - изображение 41PAUSE 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.

Use the Tab key to indent some of the lines to make your code easier to read. Indenting isn’t necessary, but it’s a good habit to acquire. As you study the code in this book, you’ll understand why indenting code lines is helpful.

Excel VBA Programming For Dummies - изображение 42A 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.

Excel VBA Programming For Dummies - изображение 43The 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.

FIGURE 34The GuessName procedure displays this dialog box When you enter the - фото 44

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 7for 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.

If you followed the previous steps, you just wrote a VBA Sub procedure, also known as a macro. When you press F5, Excel executes the code and follows the instructions. In other words, Excel evaluates each statement and does what you told it to do. (Don’t let this newfound power go to your head.) You can execute this macro any number of times — although it tends to lose its appeal after a few dozen times.

Читать дальше
Тёмная тема
Сбросить

Интервал:

Закладка:

Сделать

Похожие книги на «Excel VBA Programming For Dummies»

Представляем Вашему вниманию похожие книги на «Excel VBA Programming For Dummies» списком для выбора. Мы отобрали схожую по названию и смыслу литературу в надежде предоставить читателям больше вариантов отыскать новые, интересные, ещё непрочитанные произведения.


Отзывы о книге «Excel VBA Programming For Dummies»

Обсуждение, отзывы о книге «Excel VBA Programming For Dummies» и просто собственные мнения читателей. Оставьте ваши комментарии, напишите, что Вы думаете о произведении, его смысле или главных героях. Укажите что конкретно понравилось, а что нет, и почему Вы так считаете.

x