2011-03-11 127 views
0

我一直在試圖找出這個問題的論壇。我在每個訂單項中都有一個具有特定日期和美元價值的數據表。我想在每個月的數字和每個月創建一個美元的總和。我發現,我以爲會工作的功能,並修改它來滿足我的需求:VBA Excel計數函數中的類型不匹配錯誤

Public Function MonthOppCount(rng As Range, sdate As Date, edate As Date) As Long 

    Dim Cel As Range 
    Dim MonthCount As Integer 
    Dim MonthRev As Long 

     For Each Cel In rng 
      If Cel >= sdate And Cel < edate Then 
       ' MonthCount = MonthCount + 1 
       MonthRev = MonthRev + ActiveCell.Offset(0, -3).Value 
      End If 
     Loop 

    MonthOppCount = MonthRev 
    ActiveCell.Offset(0, 1).Value = MonthCount 

End Function 

然後我從另一個調用子程序功能:

範圍(「P5000」)值= MonthOppCount(「H5。 :H5000「,Month1,Month2)

我收到H5:H5000突出顯示的類型不匹配錯誤。有任何想法嗎?或者,一個簡單的方法來完成目標?我不能只在一個單元格中設置這個函數,因爲涉及到3個工作表,而主代碼並不是可以從中獲取這些數據的地方。

感謝, 吉賽爾

回答

3

「H5:H5000」 只是一個字符串; VBA不會自動將其轉換爲範圍。改變,從你的調用函數的行:

Range("P5000").Value = MonthOppCount("H5:H5000", Month1, Month2) 

到:

Range("P5000").Value = MonthOppCount(Range("H5:H5000"), Month1, Month2)