簡體   English   中英

Excel vba:在從該單元格調用的UDF執行之前,是否可以訪問單元格的值?

[英]Excel vba: Is it possible to access the value of a cell before the UDF called from that cell executes?

我有一個UDF,它間接從其他工作表中讀取數據,在多個工作表中添加相同的單元格,即:

Function myFunction( StrArgs As String ) As Long

  ....

End Function

我從單元格A1調用此函數,它現在的值為100:

=myFunction( ... )

計算設置為手動,並在需要時刷新工作表。

由於參數StrArgs定義了要查詢的工作表,因此我在myFunction中包含一些錯誤檢查,以防指定的工作表不存在,或者StrArgs的規范中存在錯誤。

這很好,但是我正在努力解決的問題如下:當在myFunction中發現錯誤時,我想返回(保留)調用單元的現有值,而不是零或錯誤值。

我在myFunction開頭想做的是:

existingCellValue = Application.Caller.Text   'or Application.Caller.Value

然后執行計算,並在遇到錯誤時:

myFunction = existingCellValue

但是,我發現這會返回零。 在調試器中,我看到,只要myFunction開始執行,單元格值就已經設置為零。

我的問題是 - 在執行UDF之前,有沒有辦法訪問調用單元的現有值?

- 編輯 - 更完整的代碼,作為一個例子,似乎工作正常: -

Function GETNUMBER(Col As String, Row As Integer) As Double
    Dim LookStr As String
    Dim TheAnswer As Double
    Dim CellVal As Variant

On Error GoTo errHandler

    CellVal = Application.Caller.Text

    LookStr = "=" & Col & Row
    TheAnswer = Application.Evaluate(LookStr)

    GETNUMBER = TheAnswer

    On Error GoTo 0

Exit Function

errHandler:
    GETNUMBER = CellVal

End Function

使用模塊中的上述代碼,我在工作簿中輸入以下內容:

Row
1:   | D    | 1    | =GETNUMBER(A1,B1)    | 10
2:   | D    | 2    | =GETNUMBER(A2,B2)    | 20
3:   | D    | 3    | =GETNUMBER(A3,B3)    | 30

這將從D列返回值10,20和30。

現在我將B列中的一個單元格更改為零,以調用errHandler,並返回存儲在開頭的CellVal。

這似乎有效,Application.Caller.Text和Application.ThisCell.Text都給出了正確的結果。

感謝Charles Watson和KazJaw,他們都回答了這個問題。

有幾種可能的方法,但它們都有缺點。
最簡單的方法是使用Application.Caller.Text但它返回格式化的值而不是實際值。
有關此主題的更多信息,請參閱我的博客文章http://fastexcel.wordpress.com/2012/01/08/writing-efficient-vba-udfs-part-8-getting-the-previously-calculated-value-from-該呼細胞/

您可以使用Application.ThisCell property執行此操作。 看下面很簡單的例子:

Public Function MultipleAB(a, b)
    Debug.Print Application.ThisCell.Text   'here you get current value
    MultipleAB = a * b                      'here you get new value
End Function

重要!! Application.ThisCell僅對單元格中使用的UDF有效。 在其他VBA Subs中使用時可以返回錯誤。

下圖顯示了此解決方案的工作原理(對於單元格C1和C2中隨機更改的值):

在此輸入圖像描述

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM