Excel VBA countifs工作表功能

问题描述 投票:2回答:2

我正在使用WorksheetFunction.CountIfs来计算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
Worksheets("Calculations").Range("I15").Value = Time '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)

如果我将其更改为直接在工作表(而不是VBA)中工作,那么它将使用相同的逻辑。

任何人都可以指出为什么它不在VBA工作,并建议如何解决它?

谢谢

excel vba datetime countif
2个回答
0
投票

尝试使用其他变量来设置日期和时间。 “时间”是在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)

0
投票

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

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
© www.soinside.com 2019 - 2024. All rights reserved.