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

我的问题是,自从我们上次在工作中发生事故以来,我正试图build立一个滚动计数。 下面的代码以一种方式工作。 滚动计数工作正常,但从“月份”和“分钟”中删除单词(小时,分钟,秒等)中的“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在实际格式化时间上的MMx ,但是在确定MxMMx是否需要“s”的情况下,它总是将其视为月份值。 我怎么把它分成几分钟?

x = Now() - LastLTILastLTI是最后一次事故的datex = Now() - LastLTI这一行也有一个奇怪的“故障”。 当在VBA中返回时,会返回一个额外的月份和date,但在Excel中完成后,将返回正确的值。 因此,例如,如果从lat事故(直到第二秒)的整整一天,VBA返回以下string:“00年,01月,02日,00时,00分,00秒”< – 注意由于“月”等于1,会议logging已经下降了。

我希望这解释了我想要实现的!

提前致谢

我使用了几个不同的date函数,包括DateDiff ,它返回给定间隔的两个date之间的差异 ,以及DateAdd反之,允许您指定的时间间隔添加到date值。 我也使用TimeValue函数,它只返回date的时间部分。

我认为这是得到你想要的,或者至less应该让你非常接近。

 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