excel 如何根据时间应用WorksheetFunction.CountIfs?

qco9c6ql  于 2023-01-21  发布在  其他
关注(0)|答案(2)|浏览(167)

我正在尝试计算Sheet2上的记录数。

Dim wksdata As Worksheet
Dim xyz as String
Dim Time as String

Set wksdata = Sheets("Data")

Time = Date + TimeValue("08:00:00") 'Set Time value as todays date 8am

'set calculations worksheet cell I15 as the time value
Worksheets("Calculations").Range("I15").Value = Time

'converts time column to time format
Worksheets("Data)").Range("U:U").NumberFormat = "dd/mm/yyyy hh:mm:ss"

xyz = WorksheetFunction.CountIfs(wksdata.Range("I:I"), "xyz", _
  wksdata.Range("K:K"), "C", wksdata.Range("U:U"), "<" & _
  Worksheets("Calculations").Range("I15").Value)

如果我直接在工作表中应用它,它的工作逻辑是相同的。
为什么它在VBA中不起作用?

huwehgph

huwehgph1#

尝试使用其他变量设置日期和时间。“时间”内置于VBA中,将返回当前时间和范围(“I15”)。值将设置为当前时间,而不是所需的08:00

Dim wksdata As Worksheet
Dim xyz as String
Dim startTime as String

Set wksdata = Sheets("Data")
startTime = Date + TimeValue("08:00:00") 'Set Time value as todays date 8am
Worksheets("Calculations").Range("I15").Value = startTime 'set calculations 
worksheet cell I15 as the time value

Worksheets("Data)").Range("U:U").NumberFormat = "dd/mm/yyyy hh:mm:ss"  
'converts time column to time format

xyz = WorksheetFunction.CountIfs(wksdata.Range("I:I"), "xyz", 
wksdata.Range("K:K"), "C", wksdata.Range("U:U"), "<" & 
Worksheets("Calculations").Range("I15").Value)
ncgqoxb0

ncgqoxb02#

需要将日期部分转换为长整型。完成此操作后,公式将正常工作。以下是使用类似公式完成此操作的示例:

Sub test_method()

Range("B1") = Now()
Range("B1").NumberFormat = "dd/mm/yyyy hh:mm:ss"

'Trying to calculate using a VBA date in the worksheet formula doesn't work
'This returns 0
Debug.Print WorksheetFunction.CountIfs(Range("B1:B10"), ">" & (Now() - 0.75))

'Now we change it to a long and it yields the correct answer
'returns 1
Debug.Print WorksheetFunction.CountIfs(Range("B1:B10"), ">" & CLng((Now() - 0.75)))

End Sub

相关问题