Dick Kusleika - Excel Macros For Dummies
Здесь есть возможность читать онлайн «Dick Kusleika - Excel Macros For Dummies» — ознакомительный отрывок электронной книги совершенно бесплатно, а после прочтения отрывка купить полную версию. В некоторых случаях можно слушать аудио, скачать через торрент в формате fb2 и присутствует краткое содержание. Жанр: unrecognised, на английском языке. Описание произведения, (предисловие) а так же отзывы посетителей доступны на портале библиотеки ЛибКат.
- Название:Excel Macros For Dummies
- Автор:
- Жанр:
- Год:неизвестен
- ISBN:нет данных
- Рейтинг книги:4 / 5. Голосов: 1
-
Избранное:Добавить в избранное
- Отзывы:
-
Ваша оценка:
- 80
- 1
- 2
- 3
- 4
- 5
Excel Macros For Dummies: краткое содержание, описание и аннотация
Предлагаем к чтению аннотацию, описание, краткое содержание или предисловие (зависит от того, что написал сам автор книги «Excel Macros For Dummies»). Если вы не нашли необходимую информацию о книге — напишите в комментариях, мы постараемся отыскать её.
Excel Macros For Dummies
Excel Macros For Dummies
Excel Macros For Dummies — читать онлайн ознакомительный отрывок
Ниже представлен текст книги, разбитый по страницам. Система сохранения места последней прочитанной страницы, позволяет с удобством читать онлайн бесплатно книгу «Excel Macros For Dummies», без необходимости каждый раз заново искать на чём Вы остановились. Поставьте закладку, и сможете в любой момент перейти на страницу, на которой закончили чтение.
Интервал:
Закладка:
Working with a Code Pane
As you become proficient with VBA, you spend lots of time working in Code panes. Macros that you record are stored in a module, and you can type VBA code directly into a VBA module’s Code pane.
Minimizing and maximizing windows
Code panes are much like workbook windows in Excel. You can minimize them, maximize them, resize them, hide them, rearrange them, and so on. Most people find it much easier to maximize the Code pane that they’re working on. Doing so lets you see more code and keeps you from getting distracted.
To maximize a Code pane, click the maximize button in its title bar (right next to the X). Or, just double-click its title bar to maximize it. To restore a Code pane to its original size, click the Restore button.
Sometimes, you may want to have two or more Code panes visible. For example, you may want to compare the code in two modules or copy code from one module to another. You can arrange the panes manually, or choose Window ⇒ Tile Horizontally or Window ⇒ Tile Vertically to arrange them automatically.
You can quickly switch among Code panes by pressing Ctrl+Tab. If you repeat that key combination, you keep cycling through all the open Code panes. Pressing Ctrl+Shift+Tab cycles through the panes in reverse order.
Minimizing a Code pane gets it out of the way. You can also click the pane's Close button in the title bar to close it completely. (Closing a window just hides it; you won't lose anything.) To open it again, just double-click the appropriate object in the Project Explorer. Working with these Code panes sounds more difficult than it really is.
Getting VBA code into a module
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:
Use the Excel macro recorder to record your actions and convert them to VBA code.
Enter the code directly.
Copy the code from one module and paste it into another.
Chapter 1shows you how to create code by using the Excel macro recorder. However, not all tasks can be translated to VBA by recording a macro. You often have to enter your code directly into the module. Entering code directly basically means either typing the code yourself or copying and pasting code you have found somewhere else.
Entering and editing text in a VBA module works as you might expect. You can select, copy, cut, paste, and do other things to the text.
A single line of VBA code can be as long as you like. However, you may want to use the line-continuation character 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. 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 clarify the fact that these lines are not separate statements.
The VBE has multiple levels of undo and redo. If you delete a statement that you shouldn’t have, click the Undo button on the Standard toolbar (or press Ctrl+Z) until the statement appears again. After undoing, you can click the Redo button to perform the changes you’ve undone.
Ready to enter some real, live code? Try the following steps:
1 Create a new workbook in Excel.
2 Press Alt+F11 to open 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 into the module: Sub GuessName() Dim Msg as String Dim Ans As Long 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 clairvoyant!" End Sub
6 Make sure the cursor is located anywhere within the text you typed and press F5 to execute the procedure.
The VBE has its own set of shortcut keys you can use to quickly run a command using your keyboard. F5 is a shortcut for Run ⇒ Run Sub/UserForm.
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.
If you followed the previous steps, you just created 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. You can execute this macro any number of times — although it tends to lose its appeal after a few dozen executions.
This simple macro uses the following concepts:
Defining a Sub procedure (the first line)
Declaring variables (the Dim statements)
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)
As mentioned previously, you can copy and paste code into a VBA module. For example, a Sub or Function procedure that you write for one project might also be useful in another project. Instead of reentering the code, you can open the module and use the normal copy-and-paste procedures (Ctrl+C to copy and Ctrl+V to paste). After pasting it into a VBA module, you can modify the code as necessary.
Customizing the VBE
If you’re serious about becoming an Excel programmer, you’ll spend a lot of time with VBA modules on your screen. To help make things as comfortable as possible, the VBE provides quite a few customization options.
When the VBE is active, choose Tools ⇒ Options. The Options dialog box has four tabs: Editor, Editor Format, General, and Docking. Take a moment to explore some of the options found on each tab.
The Editor tab
Figure 2-4 shows the options accessed by clicking the Editor tab of the Options dialog box. Use the option in the Editor tab to control how certain things work in the VBE.

FIGURE 2-4:The Editor tab in the Options dialog box.
The Auto Syntax Check option
The Auto Syntax Check setting determines whether the VBE opens a dialog box if it discovers a syntax error while you’re entering your VBA code. The dialog box tells roughly what the problem is. If you don’t choose this setting, VBE flags syntax errors by displaying them in a different color (red by default) from the rest of the code, and you don’t have to deal with any onscreen dialog boxes.
Читать дальшеИнтервал:
Закладка:
Похожие книги на «Excel Macros For Dummies»
Представляем Вашему вниманию похожие книги на «Excel Macros For Dummies» списком для выбора. Мы отобрали схожую по названию и смыслу литературу в надежде предоставить читателям больше вариантов отыскать новые, интересные, ещё непрочитанные произведения.
Обсуждение, отзывы о книге «Excel Macros For Dummies» и просто собственные мнения читателей. Оставьте ваши комментарии, напишите, что Вы думаете о произведении, его смысле или главных героях. Укажите что конкретно понравилось, а что нет, и почему Вы так считаете.