Home
Search
 
What's New
Index
Books
Links
Q & A
Newsletter
Banners
 
Feedback
Tip Jar
 
C# Helper...
 
XML RSS Feed
Follow VBHelper on Twitter
 
 
 
MSDN Visual Basic Community
 
 
 
 
 
TitleUse a Visual Basic function in Excel cell formulas
DescriptionThis example shows how to use a Visual Basic function in Excel cell formulas.
KeywordsVBA, Excel, formula, function
CategoriesOffice
 
Open the Tools menu, select the Macro submenu, and pick Visual Basic Editor.

Right-click on the workbook's project, open the Insert submenu, and pick Module. Add the function to the new module and save.

Now you can use the function in your worksheet cell formulas.

This example uses the following function.

 
Function Factorial(ByVal N As Integer) As Double
Dim result As Double
Dim i As Integer

    Application.Volatile True

    result = 1
    For i = 2 To N
        result = result * i
    Next i
    Factorial = result
End Function
 
The formula in cell B2 is "=Factorial(A2)" and that makes the cell display the result of the Factorial function with the contents of cell A2 as input.

If you change the function, the worksheet does not automatically update the cells' results. One way to update the values is to delete the cells' contents and then press Ctrl-Z to undo the deletion.

Doug had the following to say:

This is fine if you have one or two places where the formula is used but if there are many places it could become quite tedious if you need to change the function. I would recommend that you include the "Application.Volatile TRUE" statement in the function to force all cells to recalculate when any event causes a sheet recalculation. The default state is FALSE meaning the cell will only recalculate when one of the input parameters to the function are altered. The default parameter for Application.Volatile is TRUE so calling it without passing the Boolean value TRUE is exactly the same as calling it without any parameter.

Granted there may be cases where this can cause a serious degradation in performance if the function is quite large and takes a long time to process. In these cases you'll definitely want to weigh the advantages and disadvantages. My experience has been that these scenarios rarely present themselves and the use of the Application.Volatile statement saves far more time and frustration than it causes.

Excellent suggestion, Doug! I added the call to Application.Volatile to the original version.

Now when you make any change to any part of the worksheet, Excel updates all cells that call the function.

 
 
Copyright © 1997-2006 Rocky Mountain Computer Consulting, Inc.   All rights reserved.
  Updated