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

问题描述 投票:0回答:1

我正在使用一个基本上应该工作的易失性UDF。我将范围传递给它,如果此范围内的值发生变化,则会重新计算。但是,当我切换到另一个工作表并编辑一个单元格然后切换回来时,我看不到这个UDF的输出。

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

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

但是,如果不是非常需要,我不认为这是一个很好的解决方案,因为工作表包含数百个公式。

我也检查了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做一些事情,但我认为这不是因为这个函数参数。它必须与更改另一张纸并切换回原始纸张有关。

是的,我从表格中读取了一些值,但我也试图传递它们并且没有任何区别(我也不会改变它们)。

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

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

如果我更改工作表并在那里执行“某些操作”(如编辑单元格),则只会出现此问题。

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

excel vba user-defined-functions volatile worksheet-function
1个回答
1
投票

strTag = Cells(intTagRow, rngCell.Column).ValuestrTag = 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
© www.soinside.com 2019 - 2024. All rights reserved.