我的自定义函数使用代码成功运行,但使用公式 Returns #VALUE

My Custom Function Runs Successfully With Code, But With Formula Returns #VALUE

我创建了一个函数来获取具有给定产品编号的产品 属性。

当我从模块 运行 而不是公式时它成功地工作。

函数(已编辑):

Public Function ÖZELLİKGETİR(İsim As String, Özellik As String) As String
    Dim Okunan() As Römork
    Okunan() = VERİGETİR()

    Dim i
    MsgBox UBound(VERİGETİR()) '0
    ReDim Preserve Okunan(UBound(VERİGETİR()) + 1)
    MsgBox "Reached" 'Even this is not reached
    For i = 0 To UBound(Okunan())
    If Not Okunan(i) Is Nothing Then
    MsgBox "Reached"
        If Okunan(i).ÜrünKodu = İsim Then
        MsgBox "Reached"
            ÖZELLİKGETİR = CallByName(Okunan(i), Özellik, VbGet)
            Exit Function
        End If
    End If
    Next i

End Function

其他部分真的很长,因为它是用宏操作的;我不需要包括那些。

我的工作宏:

Sub T()
    ÖZELLİKGETİR("NM 511.136","ÜrünKodu") 'Returns "NM 511.136"
End Sub

公式:

=ÖZELLİKGETİR("NM 511.136";"ÜrünKodu") Returns #VALUE

电子表格(如果您需要其他部分): Link

我不得不查看您的工作簿以了解问题所在。对于不会说您的语言的人来说有点难:)

毕竟,这是由于@RonRosenfeld 和@AxelRichter 指出的:用户定义函数 (UDF) 有限制。

在您的 VBA 代码中,您在 ActiveSheet 上计算 很多 并且您使用了不合格的范围。例如,在您的函数 VERÝGETÝR 中,您以 Sheets("Veri Sayfasý").Activate 开始它;然后你用不合格的 Cells(r, c).

调用许多函数

看这里:

    In Sub  VERÝGETÝR(...)
        Sheets("Veri Sayfasý").Activate
        ...
        Set vRömork.DingilSayýsý = MetinOluþtur(Cells(2, i), Cells(2, i + 1))
        Set vRömork.Ton = MetinOluþtur(Cells(3, i), Cells(3, i + 1))
        Set vRömork.En = SayýOluþtur(Cells(4, i), Cells(4, i + 1))
        ...

所有这些都适用于正常 VBA,尽管甚至不推荐。 (专业人士不应该使用 Activate 东西,除非真的有必要,我几乎没有发现我们无法避免的情况)。但是,在 UDF 中,Activate 方法没有效果,它被 完全忽略 !

解决方案:重构您的代码并限定所有 RangeCells 内容。确保你从不使用ActiveSheetActivate东西。例如,您可以使用 With 子句而不是使用 Activate:

轻松重写上述代码
       With Sheets("Veri Sayfasý") // <~~ no need to activate, just a With
           Set vRömork.DingilSayýsý = MetinOluþtur(.Cells(2, i), .Cells(2, i + 1))
           Set vRömork.Ton = MetinOluþtur(.Cells(3, i), .Cells(3, i + 1))
           Set vRömork.En = SayýOluþtur(.Cells(4, i), .Cells(4, i + 1))
           ...
       End with

目前这可能是一项乏味的任务,但我强烈建议重构您的代码。我似乎是一个相当大的项目,你需要坚持良好的实践规则,以使其可维护并避免进一步的意外。