vba VBA中的时间操作
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8924099/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Time operation in VBA
提问by Andrei Ion
Here's what I want to do and I realized it wasn't working.
这就是我想要做的,但我意识到它不起作用。
If Time > 23 And Time < 7 Then
ws.Cells(Target.Row, 12).Value = 3
ElseIf Time > 7 And Time < 15 Then
ws.Cells(Target.Row, 12).Value = 1
Else
ws.Cells(Target.Row, 12).Value = 2
End If
What I want to do with this stuff... if the actual time is over 11 PM but less than 7 am... it writes 3 in a cell... and so on... The problem is that I realized that this comporison Time > 23 or Time < 7 doesn't work... how can I compare Time function with the actual hour? Thanks!
我想用这些东西做什么……如果实际时间超过晚上 11 点但不到早上 7 点……它会在一个单元格中写入 3……等等……问题是我意识到这comporison Time > 23 或 Time < 7 不起作用...如何将 Time 函数与实际小时进行比较?谢谢!
回答by Steve Robillard
Give this a try
试试这个
If Hour(now) > 23 or Hour(now) <= 7 Then
ws.Cells(Target.Row, 12).Value = 3
ElseIf Hour(now) > 7 And Hour(now) < 15 Then
ws.Cells(Target.Row, 12).Value = 1
Else
ws.Cells(Target.Row, 12).Value = 2
End If
回答by brettdj
Something like this. I have used sample variables in place of Target and knowing which sheet ws
was
像这样的东西。我使用示例变量代替 Target 并知道哪个工作表ws
是
Sub Timing()
Dim ws As Worksheet
Dim dbTime As Double
Set ws = Sheets(1)
dbTime = Time
If dbTime > 23 / 24 Or dbTime < 7 / 24 Then
ws.Cells(1, 12).Value = 3
ElseIf dbTime >= 7 / 24 And dbTime < 15 / 24 Then
ws.Cells(1, 12).Value = 1
Else
ws.Cells(1, 12).Value = 2
End If
End Sub
回答by PhilPursglove
You need to extract the hour from the time, which you can do with the DatePart
function e.g.
你需要从时间中提取小时,你可以用DatePart
函数来做,例如
Dim CurrentHour
CurrentHour = DatePart("h", Time)
If CurrentHour > 23 Or CurrentHour < 7 Then
....