使用格式功能时,“MM”代表月份与“mm”代表分钟之间的差异

时间:2014-06-21 23:24:42

标签: excel vba date excel-vba formatting

我的问题是,自从上次发生工作事故以来,我正试图设置滚动计数。下面的代码以一种方式工作。滚动计数工作正常,但删除" s"从月份和分钟的单词(小时,分钟,秒等)。

这是我的代码:

Sub LTI_Sub()

Static etime

'Exit Sub ' Uncomment to Stop

etime = Now() + TimeSerial(0, 0, 1)

Sheets("LTI").Range("Time") = LTI(Sheets("LTI").Range("Last"))

Application.OnTime etime, "LTI_Sub", , True


End Sub


Function LTI(LastLTI As Date)

x = Now() - LastLTI

Yx = Format(x, "yy")
If Yx = 1 Then
YS = ""
Else
YS = "s"
End If

Mx = Format(x, "mm")
If Mx = 1 Then
MS = ""
Else
MS = "s"
End If

Dx = Format(x, "DD")
If Dx = 1 Then
Ds = ""
Else
Ds = "s"
End If

Hx = Format(x, "HH")
If Hx = 1 Then
Hs = ""
Else
Hs = "s"
End If

MMx = Format(x, "MM")
If MMx = 1 Then
MMs = ""
Else
MMs = "s"
End If

Sx = Format(x, "SS")
If Sx = 1 Then
Ss = ""
Else
Ss = "s"
End If

LTI = Format(x, "YY \Y\e\a\r\" & YS & ", mm \M\o\n\t\h\" & MS & ", DD \D\a\y\" & Ds & "," & vbNewLine & "HH \H\o\u\r\" & Hs & ", MM \M\i\n\u\t\e\" & MMs & ", \A\n\d SS \S\e\c\o\n\d\" & Ss)

End Function

现在我不确定VBA在实际格式化时间时如何知道mmMM之间的区别,而是Mx和{{ 1}}确定是否" s"需要它,它总是将其视为月份值。我怎么说它是分钟?

还有一个奇怪的错误"行MMx(其中x = Now() - LastLTI是上次事故的日期)。在VBA中返回时,它会返回一个额外的月和日,但在Excel中完成后会返回正确的值。因此,例如,如果它自拉特事故(直至第二个)起正好1天,则VBA返回以下字符串:" 00年,01月,02天,00小时,00分钟, 00秒" < - 请注意,会议记录已经删除了S,因为"月"等于1。

我希望这能解释我想要实现的目标!

提前致谢

2 个答案:

答案 0 :(得分:2)

我使用了一些不同的日期函数,包括DateDiff,它在给定指定间隔的两个日期之间返回差异,以及DateAdd执行相反的日期函数允许您指定的时间间隔添加到日期值。我还使用TimeValue函数,它只返回日期的 time 部分。

我认为这可以得到你想要的东西,或者至少应该让你非常接近。

Function LTI(LastLTI As Date)
Dim yx As Long
Dim mx As Long
Dim dx As Long
Dim hx As Long
Dim mmx As Long
Dim sx As Long
Dim ys As String
Dim ms As String
Dim ds As String
Dim hs As String
Dim mms As String
Dim ss As String

Dim dtNow As Date
dtNow = Now()

yx = DateDiff("yyyy", dtNow, LastLTI)
ys = IIf(yx = 1, "", "s")

mx = DateDiff("m", DateAdd("yyyy", yx, dtNow), LastLTI)
ms = IIf(mx = 1, "", "s")

dx = Format(dtNow - LastLTI, "dd")
ds = IIf(dx = 1, "", "s")

hx = DateDiff("h", TimeValue(dtNow), TimeValue(LastLTI))
hs = IIf(hx = 1, "", "s")

'compute the remaining minutes not allocated to a whole hour, above:
mmx = Format(TimeValue(dtNow), "n") - Format(TimeValue(LastLTI), "n")
mms = IIf(mmx = 1, "", "s")

' compute the remaining seconds not allocated to a whole minute, above:
sx = Format(TimeValue(dtNow), "ss") - Format(TimeValue(LastLTI), "ss")
ss = IIf(sx = 1, "", "s")

LTI = yx & "\Y\e\a\r\" & ys & ", " & _
        mx & "\M\o\n\t\h\" & ms & ", " & _
        dx & "\D\a\y\" & ds & "," & vbNewLine & _
        hx & "\H\o\u\r\" & hs & ", " & _
        mmx & "\M\i\n\u\t\e\" & mms & ", \A\n\d " & _
        sx & "\S\e\c\o\n\d\" & ss

End Function

答案 1 :(得分:-1)

请尝试使用Format (expression, "mm")来代替Format (expression, "n")几分钟。