2017-04-17 127 views
2

我是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 
+0

UDF countdistinct的參數是什麼? – yass

+2

我們可以看到COUNTDISTINCTcol()的代碼嗎? –

+0

沒有看到代碼,我們無法幫到你。另外,如果它適用於「A2:A」或其他任何範圍,但不適用於「W2:W」,則我們需要查看功能代碼以及數據的外觀。 – Masoud

回答

4

GalileoCounts您使用COUNTDISTINCTcol("W2:W")。這是通過StringCOUNTDISTINCTcolCOUNTDISTINCTcol期待Range參數。所以,即使你把類似COUNTDISTINCTcol("W:W")這樣的東西也行不通 - 它需要是COUNTDISTINCTcol(Range("W:W"))

+1

另一方面 - 有時我的UDF必須被稱爲'myUDF Range(「W:W」)'而不是'myUDF(Range(「W:W」))'....是否有一個約定,當你使用一個格式在其他?它是在創建UDF時完成的,還是我如何調用它? – BruceWayne

+0

使用'Range'是隔離是對activeworkbook的activesheet的隱式引用。明確指出工作簿/工作表,然後是範圍更好。 – ThunderFrame

+1

@BruceWayne - 如果您返回'lhs = func(parms)'的值使用語法。函數(包括UDF)通常應該返回值,這樣纔是正常的語法。如果你沒有返回一個值(比如調用一個Sub,或者調用一個Function但是想忽略它的返回值),你可以使用'func parms'或'Call func(parms)'的語法。如果嘗試使用'func parms'語法,但不小心在parms周圍放置了括號(即'func(parms)'),那麼VBA將通過'parms' ByVal而不是ByRef - 這會隱式地改變'myUDF(Range(「W :W「))'是'myUDF Range(」W:W「)。值' – YowE3K