gpt4 book ai didi

excel - 调用用户定义的函数

转载 作者:行者123 更新时间:2023-12-03 01:49:55 25 4
gpt4 key购买 nike

我对 VBA 和脚本编写总体来说是新手。我能够提取资源并在 Excel 中创建一个用户定义的函数,该函数将返回数组的不同计数。当我在 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

最佳答案

GalileoCounts您正在使用COUNTDISTINCTcol("W2:W") 。那就是传递一个StringCOUNTDISTINCTcol但是COUNTDISTINCTcol期待 Range范围。所以,即使你输入类似 COUNTDISTINCTcol("W:W") 的内容它不会工作 - 它需要是 COUNTDISTINCTcol(Range("W:W")) .

关于excel - 调用用户定义的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43460170/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com