NR14
NR14

Reputation: 45

Call a user defined function

I am new to VBA and scripting in general. I was able to pull resources and create a user defined function in Excel that will return the distinct count of an array. The function is working properly when I call it within a cell in Excel.

Now, I would like to reference this function in a Macro to provide me with a message box stating the counts for two different columns. When I try to use the Macro I receive a 'Type Mismatch' error.

Not sure what I'm doing wrong - any help would be very much appreciated.

Edit: Included the COUNTDISTINCTcol code.

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

Upvotes: 2

Views: 4030

Answers (1)

YowE3K
YowE3K

Reputation: 23974

In GalileoCounts you are using COUNTDISTINCTcol("W2:W"). That is passing a String to COUNTDISTINCTcol but COUNTDISTINCTcol is expecting a Range parameter. So, even if you put something like COUNTDISTINCTcol("W:W") it wouldn't work - it would need to be COUNTDISTINCTcol(Range("W:W")).

Upvotes: 4

Related Questions