Excel VBA : Answer gets "stuck"

标签 excel vba

我是 Excel 2003 中的 VBA 新手。我编写了一个 UDF,它接受两个字符串:一个是筛选器,另一个是单元格引用。当我在 VBA 编辑器中调试并连续调用该函数几次时,一切都按我的预期运行。但是,当我在电子表格中多次使用 UDF 时,尽管输入不同,但所有使用都显示完全相同的答案。

该函数如下。它更新数据透视表,然后将值复制出单元格。但我一定是误用了它:

Function UpdatePivotAndFetchCell(catcode As String, theCell As String) As Variant
Dim ws, pt, catField, pi, theval, finalVal
Set ws = Worksheets("Reporting")
Set pt = ws.PivotTables("MyReport")
pt.RefreshTable
Set catField = pt.PivotFields("Category")

For Each pi In catField.PivotItems
    If InStr(pi.Value, catcode) Then
        pt.PivotFields("Category").CurrentPage = pi.Value
        theval = ws.Range(theCell).Value
        On Error Resume Next
        If (TypeName(theval) <> "Error") Then
            finalVal = theval
        End If
        Exit For
    End If
Next pi
UpdatePivotAndFetchCell = finalVal
End Function

如果我使用 VBA 编辑器运行它,我会得到:

Debug.Print (UpdatePivotAndFetchCell("C001", "K284"))
    'Returns 0.48
Debug.Print (UpdatePivotAndFetchCell("C002", "K284"))
    'Returns 0.52

但是在工作表中:

=UpdatePivotAndFetchCell("C001", "K284")
    (displays 0.52)
=UpdatePivotAndFetchCell("C002", "K284")
    (displays 0.52)

我可能没有正确指定函数吗?这对我来说是个谜。

最佳答案

从工作表调用的函数是 not allowed to change sheets 。否则,您可以轻松地在计算树中创建无限循环。因此,更改工作表的所有内容都会被忽略(例如 RefreshTable().CurrentPage =)并导致函数停止。

为了完整起见,有一个 workaround ,但您不应该使用它,您可以run into problems如果你这样做的话。

关于Excel VBA : Answer gets "stuck",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3622137/

相关文章:

excel - 使用 R 或 Excel 匹配字符串

VBA 循环遍历空列

excel - 防止在按钮单击时打开 VBE

excel - 为什么 VBA copytoClipboard 不再工作?

excel - 请参阅使用图标/表情符号作为名称一部分的工作表

Excel 无法隐藏超过 53 行

excel - 从 Access VBA 中搜索 Excel 列 - 类型不匹配

performance - VBA屏幕更新和效率

vba - Excel VBA Ribbon getEnabled 代码运行时未调用

regex - 如何使用 excel 正则表达式从字符串中提取广告尺寸