如果我编辑另一个 Sheet 并切换回来,则不会显示易失性 UDF 的结果

Result of volatile UDF isn't shown if I edit another Sheet and switch back

我使用的是 volatile UDF,它基本上可以正常工作。我将一个范围传递给它,如果该范围内的值发生变化,它会按原样重新计算。但是当我切换到另一个 sheet 并编辑例如一个单元格然后切换回来时,我看不到这个 UDF 的输出。

我更改了包含 UDF 的 sheet 上的单元格值或保存文件,它再次显示 UDF 的输出。我也可以做一个

' Refresh all Calculations if Sheet is activated
Private Sub Worksheet_Activate()
    Application.CalculateFull
End Sub

但如果不是迫切需要,我认为这不是一个很好的解决方案,因为 sheet 包含数百个公式。

我也检查了 UDF #Value! when switching sheets 这似乎是类似的问题(没有真正的答案)。

' Returns Tags-String based on Range/Threshold
Public Function GetTagsString(rngRange As Range) As String
    ' Define Variables
    Dim strTags As String
    Dim strTagSeparator As String
    Dim strTag As String
    Dim intTagRow As Integer
    Dim intTagValue As Integer
    Dim dblTagMinScore As Double
    Dim rngCell As Range

    ' Initialize Values
    intTagRow = Sheets("Locations").Range("TagsRow").Value
    dblTagMinScore = Sheets("Settings").Range("TagMinScore").Value
    strTagSeparator = Sheets("Settings").Range("TagSeparator").Value
    strTags = ""

    ' Loop through all Cells in Range
    For Each rngCell In rngRange
        intTagValue = rngCell.Value
        strTag = Cells(intTagRow, rngCell.Column).Value

        ' Include Tag if equal/greater than Tag-Threshold
        If (intTagValue >= dblTagMinScore) Then
            If (Not strTags = "") Then
                ' String contains already Tags => append Tag-Separator
                strTags = strTags & strTagSeparator & strTag
            Else
                strTags = strTag
            End If
        End If
    Next rngCell

    ' Return Tags-String
    GetTagsString = strTags
End Function

我通过以下方式调用此 UDF:

=GetTagsString(INDIRECT(ADDRESS(ROW();COLUMN(TagAmusement);4)):INDIRECT(ADDRESS(ROW();COLUMN(TagFun);4)))

TagAmusement 和 TagFun 是命名单元格。我知道使用 INDIRECT 可能不是最好的解决方案,但由于多种原因我需要这种动态。我在很多公式中都这样做,但没有使用 UDF,也没有同样的问题。问题一定与 UDF 有关,但我不认为这是因为这个函数参数。一定是换了一个sheet又换回原来的sheet.

是的,我从 sheet 中读取了一些值,但我也尝试传递它们,但没有任何区别(我也没有更改 (d) 它们) .

唯一有效的(在自动化基础上)是:

' Refresh all Calculations if Sheet is activated
Private Sub Worksheet_Activate()
    Application.CalculateFull
End Sub

仅当我更改 sheet 并在那里执行 "something"(如编辑单元格)时才会出现此问题。

这是 Excel 的错误还是我忽略了什么?

strTag = Cells(intTagRow, rngCell.Column).Value 等同于 strTag = ActiveSheet.Cells(intTagRow, rngCell.Column).Value

因此,如果 rngRange 在 "Sheet1" 上,但您随后切换到 "Sheet2" 并编辑单元格(这会触发重新计算),读入 strTag 的值将来自 Sheet2 而不是来自 Sheet1。如果 Sheet2 上相应的单元格碰巧是空的,那么它看起来好像 UDF 没有返回任何东西。

为防止出现这种情况,请指定对单元格的调用适用于的工作表:

strTag = rngRange.Worksheet.Cells(intTagRow, rngCell.Column).Value

或将整个 For Each 循环包装在 With...End With 块中,并使对 Cells 的调用使用该对象:

With rngRange.Worksheet
    For Each rngCell In rngRange
    '...
        strTag = .Cells(intTagRow, rngCell.Column).Value
    '...
    Next rngCell
End With