首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >调用用户定义的函数

问调用用户定义的函数
EN

Stack Overflow用户
提问于 2017-04-17 21:48:12
回答 1查看 3.9K关注 0票数 2

一般来说,我对VBA和脚本都很陌生。我能够在Excel中提取资源并创建用户定义的函数,该函数将返回数组的不同计数。当我在Excel中的单元格中调用它时,该函数正在正常工作。

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

不知道我做错了什么-任何帮助都是非常感谢的。

编辑:包括COUNTDISTINCTcol代码。

代码语言:javascript
复制
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
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-04-17 22:09:13

在GalileoCounts中,您正在使用COUNTDISTINCTcol("W2:W")。这是将一个String传递给COUNTDISTINCTcol,但是COUNTDISTINCTcol需要一个Range参数。所以,即使你把像COUNTDISTINCTcol("W:W")这样的东西放进去,它也是行不通的--它需要是COUNTDISTINCTcol(Range("W:W"))。

票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/43460170

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档