Excel 设置范围以日期作为变量

Excel set range have date as variant

我有这个代码。当我设置 rDate = Range("A14"),excel 总是理解 rDate 作为一个值而不是日期.Exampleif I set rDate as specific time (like 04/04/2017), iVal is 6.但是如果我设置</code>rDate = Range("A14"), ival = 0 `(F 列包含日期和 Range("A14") = 04/04/2017)。如何将 rDate 设置为日期?</p> <pre><code>Dim rDate As Range Set rDate = Range("A14") iLastrow = ActiveSheet.Range("A" & Rows.Count).End(xlUp).Row iVal = Application.WorksheetFunction.CountIf(Range("F1:F" & iLastrow), rDate) Sheets(1).Activate Range("C14").Value = iVal

试试下面的代码(代码注释中的解释):

Option Explicit

Sub CountIfDates()

Dim rDateRng    As Range
Dim rDate       As Double
Dim iLastrow    As Long
Dim iVal        As Long

With Worksheets("Sheet1") '<-- modify "Sheet1" to your sheet's name
    Set rDateRng = .Range("A14")
    rDate = rDateRng.Value ' <-- get the date value and store the the numeric value

    iLastrow = .Range("A" & .Rows.Count).End(xlUp).Row
    iVal = Application.WorksheetFunction.CountIf(.Range("F1:F" & iLastrow), rDate)
End With

Sheets(1).Range("C14").Value = iVal

End Sub