我是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
UDF countdistinct的參數是什麼? – yass
我們可以看到COUNTDISTINCTcol()的代碼嗎? –
沒有看到代碼,我們無法幫到你。另外,如果它適用於「A2:A」或其他任何範圍,但不適用於「W2:W」,則我們需要查看功能代碼以及數據的外觀。 – Masoud