2016-10-02 156 views
0

我想從一個單元格範圍內的函數中定義的數組中計算特定的數字。這裏是我的代碼:VBA Excel類型不匹配

Function countNumbers(cell As Range) 

    Dim rCell As Range 
    Dim myArray(25) As Integer 
    myArray(0) = 1 
    myArray(1) = 2 
    myArray(2) = 3 
    myArray(3) = 4 
    myArray(4) = 5 
    myArray(5) = 11 
    myArray(6) = 12 
    myArray(7) = 13 
    myArray(8) = 14 
    myArray(9) = 15 
    myArray(10) = 21 
    myArray(11) = 22 
    myArray(12) = 23 
    myArray(13) = 24 
    myArray(14) = 25 
    myArray(15) = 31 
    myArray(16) = 32 
    myArray(17) = 33 
    myArray(18) = 34 
    myArray(19) = 35 
    myArray(20) = 41 
    myArray(21) = 42 
    myArray(22) = 43 
    myArray(23) = 44 
    myArray(24) = 45 

    For Each rCell In cell.Cells 
     For i = LBound(myArray) To UBound(myArray) 
      If rCell.Value = myArray Then 
       countNumbers = countNumbers + 1 
      End If 
     Next i 
    Next rCell 

End Function 

我得到的錯誤是「類型不匹配」在代碼的第一行。我使用的MS-Excel 2007中感謝

+2

你的循環中,修改行'如果rCell.Value = myArray的Then'到'如果rCell.Value = myArray的(I)Then'與您試圖檢查數組中的每個單元格的標準 –

+1

另外,將Dim myArray(25)As Integer修改爲Dim myArray(24)As Integer,否則最後一個元素將爲空,並且所有空單元格都將進入您的'如果'標準。 –

+0

@ShaiRado你可以添加你的更正作爲接受它的答案,請! – KostasC

回答

1
Function countNumbers(cell As Range) 

    Dim rCell As Range 
    Dim myArray(24) As Integer 

    myArray(0) = 1 
    myArray(1) = 2 
    myArray(2) = 3 
    myArray(3) = 4 
    myArray(4) = 5 
    myArray(5) = 11 
    myArray(6) = 12 
    myArray(7) = 13 
    myArray(8) = 14 
    myArray(9) = 15 
    myArray(10) = 21 
    myArray(11) = 22 
    myArray(12) = 23 
    myArray(13) = 24 
    myArray(14) = 25 
    myArray(15) = 31 
    myArray(16) = 32 
    myArray(17) = 33 
    myArray(18) = 34 
    myArray(19) = 35 
    myArray(20) = 41 
    myArray(21) = 42 
    myArray(22) = 43 
    myArray(23) = 44 
    myArray(24) = 45 

    For Each rCell In cell.Cells 
     For i = LBound(myArray) To UBound(myArray) 
      If rCell.Value = myArray(i) Then 
       countNumbers = countNumbers + 1 
      End If 
     Next i 
    Next rCell 

End Function