使用VBA中的CountIf函数来计算具有特定月份和年份的条目数(忽略date)

我在VBA相当新。 使用Excel 2007 VBA,我试图计算在“WOMade”工作表的“H”列中有特定月份和年份的date(忽略一天)的条目数,但是我所有的方法尝试不工作。

除其他想法之外,我尝试过:

WorksheetFunction.CountIf(Sheets("WOMade").Columns("H:H"), "June-15") 

 WorksheetFunction.CountIf(Format(Sheets("WOMade").Columns("H:H"), "mmyyyy"), "062015") 

 WorksheetFunction.CountIf(Sheets("WOMade").Columns("H:H"), "June/" & "/2015) 

 WorksheetFunction.CountIfs(Sheets("WOMade").Columns("H:H"), ">=" 6/1/2015, Sheets("WOMade").Columns("H:H"), < 7/1/2015) 

有任何想法吗?

我认为最后一个例子是最接近的。

 dim i as long with Sheets("WOMade") i = WorksheetFunction.CountIfs(.Columns("H:H"), ">=" & dateserial(2015, 6, 1), .Columns("H:H"), "<" & dateserial(2015, 7, 1)) 'or, i = WorksheetFunction.CountIfs(.Columns("H:H"), ">=" & datevalue("6/1/2015"), .Columns("H:H"), "<" & datevalue("7/1/2015")) 'or, i = WorksheetFunction.CountIfs(.Columns("H:H"), ">=6/1/2015", .Columns("H:H"), "<7/1/2015") end with 

Sub Test()表格(“WOMade”)。select

  SetYear = 2015 SetMonth = 1 Count = 0 i = 1 Do While Cells(i, 8) <> "" ' Subtract for TRUE as it is stored as -1 Count = Count - (Year(Cells(i, 8)) = SetYear And Month(Cells(i, 8)) = SetMonth) i = i + 1 Loop MsgBox Count 

结束小组

 Public Function CountOfYearMonth(r As Range, y As Integer, m As Integer) As Long Set r = Intersect(r, r.Parent.UsedRange) 'Don't iterate over more than you have to 'Technically n is not necessary, you can just use CountOfYearMonth Dim n As Long, _ c As Range, _ d As Date For Each c In r.Cells If IsDate(c.Value) Then 'Does the cell contain a date? d = CDate(c.Value) 'Convert, if so If month(d) = m And year(d) = y Then 'Check year and month n = n + 1 'If match, increment total End If End If Next c CountOfYearMonth = n 'Assign return value End Function