切换到工作表时,Excel UDF返回#N / A.

时间:2016-11-03 15:08:55

标签: excel excel-vba excel-udf vba

我在excel中有一个UDF,技术上 完美无缺。但是,偶尔,当切换到具有调用该UDF的单元格的工作表时,它返回#N / A.当我打开文件然后切换到该表时,它会一直发生 我说它“完美运行”的原因是因为当我进入那个单元格并按下回车键(即手动运行该功能)时,它会返回正确的值!以及任何时候更改其中一个依赖单元格中的值 我已经尝试过故障排除以找出导致问题的原因,并且我意识到我的udf甚至没有被调用! (我在那里的debug.print语句没有打印出来)

这是我的udf:

Function AvgPrice(myWS As String, r As Range, bCol As Range, szCol As Range, ttlCol As Range)
    Application.Volatile

    Dim cell As Range, MinArb As Boolean
    Dim val As Variant, inc As Variant, thisRow As Long, iSum As Long, thisCol As Long, total As Long, price As Long
    Dim fabric As String, book As String, size As String, Lookup As String, fab As String
    Dim rLookUp As Range, cIndex As Variant

    Dim ws As Worksheet, prices As Worksheet
    Set ws = ThisWorkbook.Worksheets(myWS)
    Set prices = ThisWorkbook.Worksheets("Prices")

    Debug.Print (ws.Name)

    Set r = ws.Range(r.Address)
    Set bCol = ws.Range(bCol.Address)
    Set szCol = ws.Range(szCol.Address)
    Set ttlCol = ws.Range(ttlCol.Address)

    thisRow = r.Cells(1).row
    book = bCol.Value
    size = szCol.Value
    total = ttlCol.Value


    For Each cell In r.Cells
        inc = cell.Value
        If inc = vbNullString Then GoTo NXT
        If Not (IsNumeric(inc)) Then GoTo NXT

        thisCol = cell.Column
        fabric = getFabric2(cell, ws)

        Debug.Print (ws.Parent.Name)

        fabric = Mid(fabric, 1, 1) & LCase(Mid(fabric, 2))
        Lookup = book & "-" & size & "-" & fabric
        Set rLookUp = prices.Range("A:A")

        cIndex = Application.Match(Lookup, rLookUp, 0)
        If IsError(cIndex) Then
            Debug.Print ("1 -- Error: " & Lookup)
            Debug.Print (Err.Description)
            GoTo QuitIt
        End If
        val = prices.Cells(cIndex, 3).Value
        If val = vbNullString Or Not (IsNumeric(val)) Then
            val = prices.Cells(cIndex, 2).Value
            If val = vbNullString Or Not (IsNumeric(val)) Then GoTo NXT
        End If

        inc = inc * val
        iSum = iSum + inc
NXT:
    Next cell

QuitIt:
    If iSum > 0 Then
        AvgPrice = iSum / total
    Else
        AvgPrice = ""
    End If

End Function

1 个答案:

答案 0 :(得分:0)

我遇到了同样的问题,并通过向UDF函数传递附加参数来解决。是的,参数是要在其中调用UDF的工作表名称。