自定义VBA函数返回#NAME?

我已经写了一个VBA函数,通过将其与已知权重的项目的模型数量进行比较来计算从其模型编号中确定某个项目的权重的权重。 由于某种原因,它只返回#NAME?

这里是代码:

Function getWeight(model As String) As Double Dim weight As Double weight = -1# Dim compModel As String compModel = "" Dim prevNumMatches As Integer prevNumMatches = 0 Dim numMatches As Integer numMatches = 0 Dim i As Integer Dim p As Integer Dim samePump As Boolean Dim sameMotor As Boolean Dim special As Boolean For i = 2 To 1000 compModel = CStr(Sheets("Weights").Cells(i, 1).Value) For p = 1 To Len(compModel) samePump = False sameMotor = False special = False numMatches = 0 If p = 1 Then If Mid(model, p, 1) = Mid(compModel, p, 1) Then samePump = True numMatches = numMatches + 1 End If ElseIf p = 5 Then If Mid(model, p, 1) <> "-" Then special = True End If If Mid(model, p, 1) = Mid(compModel, p, 1) Then numMatches = numMatches + 1 End If ElseIf p = 9 Then If Mid(model, p, 1) = Mid(compModel, p, 1) Then sameMotor = True numMatches = numMatches + 1 End If Else If Mid(model, p, 1) = Mid(compModel, p, 1) Then numMatches = numMatches + 1 End If End If If samePump And (sameMotor Or special) Then If numMatches > prevNumMatches Then weight = CDbl(Sheets("Weights").Cells(i, 2).Value) prevNumMatches = numMatches ElseIf numMatches = prevNumMatches Then If CDbl(Sheets("Weights").Cells(i, 2).Value) > weight Then weight = CDbl(Sheets("Weights").Cells(i, 2).Value) End If End If End If Next p Next i If weight = -1# Then getWeight = 0# Else getWeight = weight End If End Function 

为什么这不会像我预期的那样返回一个数字?

每次迭代

 p = 1 to len(compmodel) 

循环将所有的布尔值重置为false。 这意味着声明

 If samePump And (sameMotor Or special) Then 

永远不会是真的,因为它永远不会评估所有那些在同一个循环的通行证。 将布尔setter放在循环的开始之前,而不是在它之前。

 samePump = False sameMotor = False special = False numMatches = 0 For p = 1 To Len(compModel) 

另外,如果你想使用debugging器只是运行这个。 这样,您可以逐行浏览代码,看看发生了什么事情。

 Sub main() Dim THingy As Double THingy = getWeight("R221-FT-AA1") MsgBox (THingy) End Sub 

该函数是(隐式) Public ,所以获得#NAME?的唯一方法#NAME? 错误是在错误types的模块中实现它,使得Excel不知道=getWeight指的是什么。

您需要将一个标准程序模块(.bas)添加到您的项目中,剪切该function并将其粘贴到该项目中。

除了错误 ,你应该可以从工作表中调用你的UDF。

ThisWorkbook ,以及所有的Worksheet模块, UserForm模块和普通类模块,是对象的 蓝图 ,这意味着为了调用他们的公共成员,你需要使用该类的实例来限定成员调用…和UDF (或者对于这个问题,macros)电话不能这样做。

我发现了这个问题。 即使该文件保存为启用macros的工作簿(.xlsm)macros未启用。 当我今天早上重新打开它时,它给了我启用macros的选项。 一旦我这样做,并按Jared的build议更正了代码,就可以按计划进行。