【问题标题】:User defined function returning circular reference用户定义函数返回循环引用
【发布时间】:2014-07-15 21:50:06
【问题描述】:

在excel中我有以下
a1 = "a" b1:b3 = {=UDFtest(A1:A3)}
a2 = "b"
a3 = "c"

Public Function UDFtest(labelsRange As Range)
'    myCaller = Application.Caller
'    outputNumRows = UBound(myCaller, 1) - LBound(myCaller, 1) + 1
'    outputNumCols = UBound(myCaller, 2) - LBound(myCaller, 2) + 1

    myNumRows = 3
    myData = Array(Array(1), Array(2), Array(3))
    myLabels = Array("a", "b", "c")

'    If myNumRows = outputNumRows Then
        For i = 0 To myNumRows - 1
            If labelsRange.Cells(i + 1, 1).Value <> myLabels(i) Then
                myData(i, 0) = xlErrRef
            End If
        Next i
'    Else
'        UDFtest = xlErrRef
'        Exit Function
'    End If

    UDFtest = myData
End Function

'myData' 和 'myLabels' 将通过 api 调用提供给我。我的目标是在检查用户的标签是否正确后返回 myData。

上面的代码按预期工作,(因为我已经注释掉了多余的行)。 但是,如果我取消注释这些行,excel 会给我一个循环引用错误。

如何修复循环引用?

【问题讨论】:

    标签: excel user-defined-functions circular-reference vba


    【解决方案1】:

    循环引用由 Application.Caller 触发。

    您可以通过将输入范围读入数组来更简单地读取 UDF 参数的值。

    Public Function UDFtest(labelsRange As Range)
     Dim bHas0Base As Boolean
     Dim outputNumRows As Long, outputNumCols As Long, i As Long
     Dim myData As Variant, myLabels As Variant, labelValues As Variant
    
     Const NUM_ROWS As Long = 3
    
     If TypeName(Application.Caller) <> "Range" Then
        UDFtest = CVErr(xlErrRef)
        Exit Function
     End If
    
     '--myData and myLabels will be returned from API calls
     myData = Array(Array(1), Array(2), Array(3))
     myLabels = Array("a", "b", "c")
     '--to allow either Option Base
     bHas0Base = LBound(myLabels) = 0
    
     '--read range values into 1-based 2D array
     labelValues = labelsRange.Value
     If Not IsArray(labelValues) Then
         ReDim labelValues(1, 1)
         labelValues(1, 1) = labelsRange.Value
     End If
     outputNumRows = UBound(labelValues, 1)
     outputNumCols = UBound(labelValues, 2) 'not used yet
    
     If outputNumRows = NUM_ROWS Then
       For i = 1 To outputNumRows
          If labelValues(i, 1) <> myLabels(i + bHas0Base) Then
               myData(i + bHas0Base)(0) = CVErr(xlErrRef)
           End If
       Next i
       Else
          UDFtest = CVErr(xlErrRef)
          Exit Function
       End If
     UDFtest = myData
    End Function
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-05-27
      • 1970-01-01
      • 1970-01-01
      • 2021-05-10
      • 2023-02-07
      • 2021-09-28
      • 1970-01-01
      • 2014-11-28
      相关资源
      最近更新 更多