我在 excel 中有一个 UDF,它在技术上 非常完美。但是,有时,当切换到具有调用该 UDF 的单元格的工作表时,它会返回 #N/A。当我打开文件然后切换到该工作表时,它始终如一地发生。
我说它“完美运行”的原因是因为当我进入该单元格并按 Enter 键(即手动运行该函数)时,它确实返回了正确的值!以及任何时候更改依赖单元格之一中的值。
我已经尝试排除故障以找出导致问题的原因,并且我意识到我的 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