Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
Excel_2010_Bible.pdf
Скачиваний:
26
Добавлен:
13.03.2015
Размер:
11.18 Mб
Скачать

Chapter 39: Introducing Visual Basic for Applications

As macros go, this example is okay, but it’s certainly not perfect. It’s not very flexible, and it doesn’t include any error handling. For example, if the workbook structure is protected, trying to add a new sheet will cause an error.

Learning More

This chapter barely scratches the surface of what you can do with VBA. If this is your first exposure to VBA, you’re probably a bit overwhelmed by objects, properties, and methods. I don’t blame you. If you try to access a property that an object doesn’t have, you get a run-time error, and your VBA code grinds to a screeching halt until you correct the problem. Fortunately, several good ways are available to learn about objects, properties, and methods.

Read the rest of the book. Subsequent chapters in this section contain additional information and many more examples.

Record your actions. The best way to become familiar with VBA is to turn on the macro recorder and record actions that you make in Excel. You can then examine the code to gain some insights regarding the objects, properties, and methods.

Use the Help system. The main source of detailed information about Excel’s objects, methods, and procedures is the VBA Help system. Help is very thorough and easy to access. When you’re in a VBA module, just move the cursor to a property or method and press F1. You get help that describes the word that is under the cursor.

Get another book. Several books are devoted exclusively to using VBA with Excel. My book, Excel 2010 Power Programming with VBA (Wiley), is one.

821

CHAPTER

Creating Custom

Worksheet Functions

As mentioned in the preceding chapter, you can create two types of VBA procedures: Sub procedures and Function procedures. This chapter focuses on Function procedures.

Overview of VBA Functions

Function procedures that you write in VBA are quite versatile. You can use these functions in two situations:

You can call the function from a different VBA procedure.

You can use the function in formulas that you create in a worksheet.

This chapter focuses on creating functions for use in your formulas.

Excel includes hundreds of predefined worksheet functions. With so many from which to choose, you may be curious as to why anyone would need to develop additional functions. The main reason is that creating a custom function can greatly simplify your formulas by making them shorter, and shorter formulas are more readable and easier to work with. For example, you can often replace a complex formula with a single function. Another reason is that you can write functions to perform operations that would otherwise be impossible.

Note

This chapter assumes that you’re familiar with entering and editing VBA code in the Visual Basic Editor (VB Editor). See Chapter 39 for an overview of the VB Editor. n

IN THIS CHAPTER

Overview of VBA functions About function procedures Function procedure arguments Debugging custom functions Pasting custom functions

823

Part VI: Programming Excel with VBA

An Introductory Example

Creating custom functions is relatively easy after you understand VBA. Without further ado, here’s an example of a VBA function procedure. This function is stored in a VBA module, which is accessible from the VB Editor.

A custom function

This example function, named NumSign, uses one argument. The function returns a text string of Positive if its argument is greater than 0 (zero), Negative if the argument is less than 0, and Zero if the argument is equal to 0. The function is shown in Figure 40.1.

FIGURE 40.1

A simple custom worksheet function.

You can, of course, accomplish the same effect with the following worksheet formula, which uses a nested IF function:

=IF(A1=0,”Zero”,IF(A1>0,”Positive”,”Negative”))

Many would agree that the custom function solution is easier to understand and to edit than the worksheet formula.

Using the function in a worksheet

When you enter a formula that uses the NumSign function, Excel executes the function to get the result. This custom function works just like any built-in worksheet function. You can insert it in a formula by choosing Formulas Function Library Function Wizard, which displays the Insert Function dialog box. (Custom functions are listed in the User Defined category.) When you select

824

Chapter 40: Creating Custom Worksheet Functions

the function from the list, you can then use the Function Arguments dialog box to specify the arguments for the function, as shown in Figure 40.2. You also can nest custom functions and combine them with other elements in your formulas.

FIGURE 40.2

Creating a worksheet formula that uses a custom function.

Analyzing the custom function

This section describes the NumSign function. Here again is the code:

Function NumSign(num)

Select Case num

Case Is < 0

NumSign = “Negative”

Case 0

NumSign = “Zero”

Case Is > 0

NumSign = “Positive”

End Select

End Function

Notice that the procedure starts with the keyword Function, followed by the name of the function (NumSign). This custom function uses one argument (num), and the argument’s name is enclosed in parentheses. The num argument represents the cell or variable that is to be processed. When the function is used in a worksheet, the argument can be a cell reference (such as A1) or a literal value (such as –123). When the function is used in another procedure, the argument can be a numeric variable, a literal number, or a value that is obtained from a cell.

The NumSign function uses the Select Case construct (described in Chapter 39) to take a different action, depending on the value of num. If num is less than 0, NumSign is assigned the text Negative. If num is equal to 0, NumSign is Zero. If num is greater than 0, NumSign is Positive. The value returned by a function is always assigned to the function’s name.

825

Соседние файлы в предмете [НЕСОРТИРОВАННОЕ]