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


1

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:

https://support.microsoft.com/en-us/topic/description-of-limitations-of-custom-functions-in-excel-f2f0ce5d-8ea5-6ce7-fddc-79d36192b7a1

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.

Note:

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

MORE FROM ALLEN

Superscripts in Custom Formats

When you create custom formats for your data, Excel provides quite a few ways you can make that data look just as you ...

Discover More

Pausing Macros for User Input

Does your macro need to get some input from a user? Here are the ways that Excel provides for that input to be solicited.

Discover More

Calculating Differences in Months using Non-Standard Date Values

Dates can be entered into a worksheet in any number of unique or novel ways. Working with those dates can be a challenge, ...

Discover More

Excel Smarts for Beginners! Featuring the friendly and trusted For Dummies style, this popular guide shows beginners how to get up and running with Excel while also helping more experienced users get comfortable with the newest features. Check out Excel 2013 For Dummies today!

More ExcelTips (ribbon)

Getting Rid of the "Enable Macros" Notice

Do you get tired of the dialog box that says "do you want to enable macros" that is displayed when you open a workbook. ...

Discover More

Recovering Macros from Corrupted Workbooks

Workbooks get corrupted from time to time; that's a fact of life in an Excel world. If those corrupted workbooks contain ...

Discover More

Notification when Recalculation is Done

If you manually recalculate your workbooks, you are probably doing so because of the time it takes to do the ...

Discover More
Subscribe

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

View most recent newsletter.

Comments

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 one less than 9?

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.
See https://sites.google.com/view/MyExcelToolbox
and http://dailydoseofexcel.com/archives/2015/03/05/why-not-let-users-trigger-macros-from-a-udf/#comment-1130479


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
Subscribe

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.