在Excel中,我需要自定义格式化单元格以显示时间为hh:mm,但是它会在0:00返回

我希望能够在单元格中input“1830”,并让Excel自动将其转换为18:30的格式。

我试图使用自定义格式和时间来格式化单元格,我无法使其工作。 请在发布之前自己尝试一下,我需要做的就是inputhh:mm。

我猜,我将需要使用VBA,我不是很熟悉,但想学习。 我知道我可以右键单击“Sheet1”,转到“查看源代码”,并确保顶部select了“工作表”而不是“常规”,然后代码。 如果有人可以粘贴代码,将不胜感激!

谢谢!

创build此自定义格式并应用于选定的单元格:0 \:00

如果你想在Excel中使用当前时间,可以按Ctrl + Shift + ; 在一个牢房里,把时间放在牢房里

要做到这一点,你必须首先想出一些规则来将整数值转换成时间值。 一些问题:

如果有人input7,你想离开那个7,还是你想把它转换成00:07?

如果有人input1861,是否要将其转换为19:01?

如果有人input1830.5,你想把它转换成18:30:30吗?

这只会影响A1,但是你可以改变rAffected为你想要的范围。

Private Sub Worksheet_Change(ByVal Target As Range) Dim rAffected As Range 'You may want to limit which cells change Set rAffected = Me.Range("A1") If Not Intersect(Target, rAffected) Is Nothing Then Application.EnableEvents = False Target.Value = TimeSerial(Left$(Target.Value2, Len(Target.Value2) - 2), Right$(Target.Value2, 2), 0) Application.EnableEvents = True End If End Sub 

这很简单。 您只需在一个单元格中键入18:30,Excel就会为您完成剩下的工作。

我有类似的需求。 用户使用数字键盘input24小时,冒号input是一个痛苦的对接…

这是一种矫枉过正,但它适用于我的情况。 您只需使用24小时制格式之一格式化所需的单元格即可:

  Public Sub Handle24HourTimeEntry(ByVal Target As Range) 'Converts up to 4 digits to 24 hour time Dim sTime24 As String Const sTIME_FORMATS As String = "|h:mm;@|h:mm|hh:mm|" Const sERROR_VALUE As String = "XXXX" 'Valid 24hr time values: 1, 59, 135, 2035, 2359 'Invalid values: 2400, 90, 9999, 12345 If Target.Cells.Count = 1 Then ' ensure that only single cell edits get processed If IsNumeric(Target.Cells.Value2) Then ' skips empty cells, labels and error conditions If Not Target.Cells.HasFormula Then ' skip formulas If InStr(1, sTIME_FORMATS, "|" & Target.Cells.NumberFormat & "|") > 0 Then If Target.Value2 >= 1 Then ' it's not a standard time value sTime24 = Format$(Target.Value2, "0000") If Len(sTime24) = 4 Then sTime24 = Left$(sTime24, 2) & ":" & Mid$(sTime24, 3, 2) If IsDate(sTime24) Then Target.Value2 = CDate(sTime24) Else Target.Value = sERROR_VALUE End If Else Target.Value = sERROR_VALUE End If End If End If End If End If End If End Sub 

我从工作簿更改事件中调用它:

 Private Sub Workbook_SheetChange(ByVal Sh As Object, ByVal Target As Range) Handle24HourTimeEntry Target End Sub