首頁 > 後端開發 > C++ > 主體

如何修改 Excel UDF 中的儲存格而不傳回數組?

Mary-Kate Olsen
發布: 2024-11-14 16:59:02
原創
809 人瀏覽過

How to Modify Cells in Excel UDFs Without Returning an Array?

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中文網其他相關文章!

來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板