VBA:如何在Excel宏中调用用户定义函数

问题描述:

我是VBA和一般脚本编程的新手。我能够在Excel中获取资源并创建用户定义的函数,以返回数组的不同数量。当我在Excel中的单元格中调用该函数时,该功能正常工作。VBA:如何在Excel宏中调用用户定义函数

现在,我想在宏中引用这个函数来为我提供一个消息框,说明两个不同列的计数。当我尝试使用宏时,我收到'类型不匹配'错误。

不知道我在做什么错 - 任何帮助将非常感激。

编辑:包括COUNTDISTINCTcol代码。

Sub GalileoCounts() 

    Dim teachers As Long 
    Dim students As Long 

    teachers = COUNTDISTINCTcol("W2:W") 'ERROR HERE for "W2:W" 
    students = COUNTDISTINCTcol("A2:A") 'ERROR with "A2:A" as well 

    MsgBox "Teachers: " & teachers & vbNewLine & "Students: " & students, 
    vbOKOnly, "Galileo Counts" 

End Sub 
---- 
Public Function COUNTDISTINCTcol(ByRef rngToCheck As Range) As Variant 

Dim colDistinct As Collection 
Dim varValues As Variant, varValue As Variant 
Dim lngCount As Long, lngRow As Long, lngCol As Long 

On Error GoTo ErrorHandler 

varValues = rngToCheck.Value 

'if rngToCheck is more than 1 cell then 
'varValues will be a 2 dimensional array 
If IsArray(varValues) Then 

    Set colDistinct = New Collection 

    For lngRow = LBound(varValues, 1) To UBound(varValues, 1) 
     For lngCol = LBound(varValues, 2) To UBound(varValues, 2) 

      varValue = varValues(lngRow, lngCol) 

      'ignore blank cells and throw error 
      'if cell contains an error value 
      If LenB(varValue) > 0 Then 

       'if the item already exists then an error will 
       'be thrown which we want to ignore 
       On Error Resume Next 
       colDistinct.Add vbNullString, CStr(varValue) 
       On Error GoTo ErrorHandler 

      End If 

     Next lngCol 
    Next lngRow 

    lngCount = colDistinct.Count 
Else 
    If LenB(varValues) > 0 Then 
     lngCount = 1 
    End If 

End If 

COUNTDISTINCTcol = lngCount 

Exit Function 

ErrorHandler: 
    COUNTDISTINCTcol = CVErr(xlErrValue) 

End Function 
+0

UDF countdistinct的参数是什么? – yass

+2

我们可以看到COUNTDISTINCTcol()的代码吗? –

+0

没有看到代码,我们无法帮到你。另外,如果它适用于“A2:A”或其他任何范围,但不适用于“W2:W”,则我们需要查看功能代码以及数据的外观。 – Masoud

GalileoCounts您使用COUNTDISTINCTcol("W2:W")。这是通过StringCOUNTDISTINCTcolCOUNTDISTINCTcol期待Range参数。所以,即使你把类似COUNTDISTINCTcol("W:W")这样的东西也行不通 - 它需要是COUNTDISTINCTcol(Range("W:W"))

+1

另一方面 - 有时我的UDF必须被称为'myUDF Range(“W:W”)'而不是'myUDF(Range(“W:W”))'....是否有一个约定,当你使用一个格式在其他?它是在创建UDF时完成的,还是我如何调用它? – BruceWayne

+0

使用'Range'是隔离是对activeworkbook的activesheet的隐式引用。明确指出工作簿/工作表,然后是范围更好。 – ThunderFrame

+1

@BruceWayne - 如果您返回'lhs = func(parms)'的值使用语法。函数(包括UDF)通常应该返回值,这样才是正常的语法。如果你没有返回一个值(比如调用一个Sub,或者调用一个Function但是想忽略它的返回值),你可以使用'func parms'或'Call func(parms)'的语法。如果尝试使用'func parms'语法,但不小心在parms周围放置了括号(即'func(parms)'),那么VBA将通过'parms' ByVal而不是ByRef - 这会隐式地改变'myUDF(Range(“W :W“))'是'myUDF Range(”W:W“)。值' – YowE3K