VBA:如何在Excelmacros中调用用户定义的函数

我是VBA和一般脚本的新手。 我能够拉动资源,并在Excel中创build一个用户定义的函数,它将返回一个数组的不同数量。 当我在Excel中的单元格中调用该函数时,该function正常工作。

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

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

编辑:包括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 

GalileoCounts您正在使用COUNTDISTINCTcol("W2:W") 。 这是传递一个StringCOUNTDISTINCTcolCOUNTDISTINCTcol期待一个Range参数。 所以,即使你把像COUNTDISTINCTcol("W:W")这样的东西,它不会工作 – 它需要是COUNTDISTINCTcol(Range("W:W"))