Excel UDFs: Modifying Cells Without Returning Arrays
One of the limitations of user-defined functions (UDFs) in Excel is their inability to directly modify cells or workbook properties. However, a workaround exists, albeit complex, that allows UDFs to achieve cell modification.
Using Windows and Application Timers to Circumvent UDF Restrictions
To modify cells from within a UDF, a clever combination of Windows timers and Application.OnTime timers is employed. The Windows timer initiates an Application.OnTime timer, which executes code safely when Excel allows cell modifications.
Implementation
The UDF calls the Windows timer routine, which schedules an Application.OnTime timer with a specific time parameter. The Application.OnTime routine then executes code that cannot be performed within the UDF itself.
Example Code
The following code demonstrates how this workaround is implemented:
Public Function AddTwoNumbers(ByVal Value1 As Double, ByVal Value2 As Double) As Double AddTwoNumbers = Value1 + Value2 ' Schedule the Windows timer mWindowsTimerID = SetTimer(0&, 0&, 1, AddressOf AfterUDFRoutine1) End Function Public Sub AfterUDFRoutine1() ' Schedule the Application.OnTime timer mApplicationTimerTime = Now Application.OnTime mApplicationTimerTime, "AfterUDFRoutine2" End Sub Public Sub AfterUDFRoutine2() ' Perform modifications outside the UDF '... End Sub
Caveats
This workaround is not without limitations. UDFs employing it should not be volatile, pass volatile functions, or reference cells containing volatile formulas/functions. Additionally, cell modifications will only occur when the timer triggers in a safe environment (no open dialogs or cell editing).
The above is the detailed content of Can Excel UDFs Modify Cells Without Returning Arrays?. For more information, please follow other related articles on the PHP Chinese website!