Excel UDF: Modifying Cells Without Returning an Array
In Excel, User Defined Functions (UDFs) typically return values or arrays. However, there are scenarios where a UDF needs to modify other cells without returning an array. This can be achieved through a complex technique that involves Windows timers and Application.OnTime events.
The Issue:
Consider a UDF named New_Years that takes two years as input and returns an array of New Year's Day dates between those years. However, to populate the array in Excel, the user must manually select cells, enter the formula, and press Ctrl + Shift + Enter. This limitation prevents the UDF from automatically filling out the dates.
The Solution:
Despite Excel's restriction on UDFs modifying cells directly, a workaround using Windows timers and Application.OnTime events makes it possible. By starting a Windows timer from within the UDF, a subsequent Application.OnTime timer can be scheduled to execute actions that would otherwise be forbidden in a UDF.
Code Example:
The following code demonstrates how to implement this technique using a Collection to store the references of cells where the UDF is called. Two timer routines, AfterUDFRoutine1 and AfterUDFRoutine2, are used to handle the timer events.
Public Sub AfterUDFRoutine1() ' Stop the Windows timer If mWindowsTimerID <> 0 Then KillTimer 0&, mWindowsTimerID ' Cancel any previous OnTime timers If mApplicationTimerTime <> 0 Then Application.OnTime mApplicationTimerTime, "AfterUDFRoutine2", , False End If ' Schedule timer mApplicationTimerTime = Now Application.OnTime mApplicationTimerTime, "AfterUDFRoutine2" End Sub Public Sub AfterUDFRoutine2() Dim Cell As Range ' ... Do tasks not allowed in a UDF ... End Sub
Usage:
To apply this technique, a UDF (e.g., AddTwoNumbers) can be created within a regular module. Within the UDF, the timer routines are started and the cell reference of the calling cell is stored in the Collection. The timer routines subsequently modify the required cells outside the UDF's scope.
By leveraging Windows timers and Application.OnTime events, it becomes possible to create UDFs that modify cells without returning an array. This technique allows for greater automation and eliminates the need for manual array filling by the user.
以上是如何修改 Excel UDF 中的儲存格而不傳回數組?的詳細內容。更多資訊請關注PHP中文網其他相關文章!