Calling a Subroutine from a UDF

Written by Allen Wyatt (last updated May 21, 2022)
This tip applies to Excel 2007, 2010, 2013, 2016, 2019, Excel in Microsoft 365, and 2021


Yair has two macros in a workbook: a UDF and a subroutine that (among other things) adds a worksheet to the workbook. He cannot seem to call the subroutine from within the UDF, so he wonders if there is a restriction about using CALL within a UDF. If there is, he wonders why, and if there isn't, he wonders what he can do to call the subroutine.

You can, within a UDF (user-defined function) use the CALL statement; VBA (and Excel) allow you to do this. What you cannot do during the execution of a UDF or a subroutine called by a UDF is to modify the Excel environment. This means you cannot take an action that modifies the worksheet structure or the workbook structure. That's not all, though; there are other things that cannot be done while a UDF is running. These are detailed at this Microsoft site:

Note that the article indicates it is applicable to Excel 2010, though it is also applicable to all other modern versions of Excel. Note, as well, that the reason a UDF cannot modify the Excel environment is because that is not their purpose—they are intended to augment Excel's built-in suite of functions, which also don't modify the Excel environment. Functions (built-in or user-define) are intended to return values.

The bottom line in Yair's case is that the CALL function is just fine, but what is being done during the CALL function (adding a worksheet to the workbook) is not fine—that is where the hang-up is. So, how would you go about doing what Yair wants done? I think the best way would be to restructure the relationship between the UDF and the subroutine. Let's say, for instance, that Yair's subroutine (the one that, among other things, adds a worksheet) is called MyRoutine. Yair could structure that subroutine in this manner:

Dim bFlag As Boolean

Sub MyRoutine()

    ' define the variables and constants you want to use

    If bFlag Then
        ' add worksheet and do other things you cannot
        ' do in the UDF
        bFlag = False         ' reset the flag to False
    End If

    ' do other things you need to do

    ' reset the timer:
    Application.OnTime Now() + TimeValue("00:01:00"), "MyRoutine"
End Sub

In this instance, the bFlag variable is set outside of any procedure, but it is still within the module. That way the value of the variable can be accessed by all of the procedures within the module.

Next, a timer needs to be set (using the OnTime method) to run MyRoutine at some future point. If you wanted to set the timer manually, you could use a short macro such as this:

Sub SetTimer()
    Application.OnTime Now() + TimeValue("00:01:00"), "MyRoutine"
End Sub

Or, you could add the single line of code to an event handler, such as the Workbook_Open so that it is automatically executed when the workbook is opened. Once the timer is set, then MyRoutine runs (in this case) every minute. The value of the bFlag variable is checked in the subroutine, and if it is True, then the things you had wanted to do in the UDF are executed.

All that is left to do is to add this line to your UDF:

bFlag = True

The Boolean flag is set, and the next time MyRoutine is executed, you'll get the desired changes to your workbook. And, since the changes occur outside of the UDF, then both VBA and Excel are happy.


If you would like to know how to use the macros described on this page (or on any other page on the ExcelTips sites), I've prepared a special page that includes helpful information. Click here to open that special page in a new browser tab.

ExcelTips is your source for cost-effective Microsoft Excel training. This tip (12892) applies to Microsoft Excel 2007, 2010, 2013, 2016, 2019, Excel in Microsoft 365, and 2021.

Author Bio

Allen Wyatt

With more than 50 non-fiction books and numerous magazine articles to his credit, Allen Wyatt is an internationally recognized author. He is president of Sharon Parq Associates, a computer and publishing services company. ...


Determining the Hour of the Day

Need to know the current hour of the day? You can derive the information in your macros by using the Hour function, as ...

Discover More

Preventing Jumbled Sorts

Click the Sort tool in Excel, and you may be surprised that the data in your worksheet is jumbled. In order to sort ...

Discover More

Adding Quoted Words to an Index

It is not unusual to need to convert one notation in a document into another entirely different notation. For instance, ...

Discover More

Professional Development Guidance! Four world-class developers offer start-to-finish guidance for building powerful, robust, and secure applications with Excel. The authors show how to consistently make the right design decisions and make the most of Excel's powerful features. Check out Professional Excel Development today!

More ExcelTips (ribbon)

Comparing Strings

As your macro is processing information, there will doubtless be times that it will need to compare information in ...

Discover More

Creating a Plus/Minus Button

Want a quick way to convert positive values to negative and vice versa? You can create your own plus/minus button by ...

Discover More

Self-Deleting Macros

Macros are very powerful, but you may not want them to always be available to a user. Here are some ways you can limit ...

Discover More

FREE SERVICE: Get tips like this every week in ExcelTips, a free productivity newsletter. Enter your address and click "Subscribe."

View most recent newsletter.


If you would like to add an image to your comment (not an avatar, but an image to help in making the point of your comment), include the characters [{fig}] (all 7 characters, in the sequence shown) in your comment text. You’ll be prompted to upload your image when you submit the comment. Maximum image size is 6Mpixels. Images larger than 600px wide or 1000px tall will be reduced. Up to three images may be included in a comment. All images are subject to review. Commenting privileges may be curtailed if inappropriate images are posted.

What is two more than 4?

2022-05-21 12:16:47

J. Woolley

A UDF is a VBA Function that is referenced in a cell formula. Excel imposes several restrictions as described in the Tip.
A UDF will return an error if it initiates Application.OnTime directly or indirectly (by use of a Sub). The Tip cleverly avoids this problem by continuously initiating OnTime before (and after) a UDF might want to use it. This is not very efficient, especially if a worksheet references several such UDFs that have different purposes. The Tip's OnTime resolution is 1 minute (a significant delay); the minimum OnTime resolution is about 1 second. And OnTime cannot start a Sub that takes parameters.
However, a UDF can use Windows API functions SetTimer and KillTimer for delayed initiation of a procedure that might otherwise be prohibited. My Excel Toolbox includes Sub RunMacroDelayed_Do(Macro) to add the procedure named Macro to a FIFO queue of delayed procedures that will run after a 1 millisecond delay. Macro can include text, numeric, and/or logical arguments. For example:
    Macro = "MyMacro ""Hello World"",3.14,FALSE"
Macro must not be defined in a Class Module or UserForm.
Here is a UDF that uses a delayed Sub to add a worksheet to the active workbook (as requested by Yair):

Function MyUDF(SheetName)
    Const Q = """" ' one quotation mark (")
    RunMacroDelayed_Do "AddSheet " & Q & SheetName & Q
    MyUDF = "added sheet " & SheetName
End Function

Sub AddSheet(SheetName)
    Worksheets.Add.Name = SheetName
End Sub

Here are a few My Excel Toolbox UDFs that use delayed procedures to avoid restrictions imposed by Excel: CalcMode, SetChars, SetFill, SetFont, SetNumberFormat, SetStyle, SpillArray.

This Site

Got a version of Excel that uses the ribbon interface (Excel 2007 or later)? This site is for you! If you use an earlier version of Excel, visit our ExcelTips site focusing on the menu interface.

Newest Tips

FREE SERVICE: Get tips like this every week in ExcelTips, a free productivity newsletter. Enter your address and click "Subscribe."

(Your e-mail address is not shared with anyone, ever.)

View the most recent newsletter.