【问题标题】:How to combine Day and Hour into one Date如何将日和小时合并为一个日期
【发布时间】:2012-04-26 21:40:17
【问题描述】:

我有三个文本框(分别代表日期、小时、分钟)

我需要将最后的 Day/Month/Year Hour:Minute 粘贴到 Excel 中的一个单元格中 将其格式化为日期

sDate = Format(myDate.Value & txtHour.Value & txtMinute.Value, "MM/DD/YYYY HH:MM")
.Cells(iRow, iCol + 1).Value = sDate

帮帮我?我在挠头。

它是这样出来的。

04/26/20121437

【问题讨论】:

    标签: excel vba date


    【解决方案1】:

    如果您的日期已经是 04/26/27 的格式,您应该可以执行类似的操作

    sDate = myDate.Value & " " & txtHour.Value & ":" & txtMinute.Value
    .Cells(iRow, iCol + 1).Value = sDate
    

    sDate = Format(myDate.Value, "MM/DD/YYYY") & " " & txtHour.Value & ":" & txtMinute.Value
    .Cells(iRow, iCol + 1).Value = sDate
    

    【讨论】:

    • 如果 OP 需要一个两位数表示小时和分钟的唯一问题
    • + 1 :) 您可能想像史蒂夫建议的那样将 sDate = myDate.Value & " " & txtHour.Value & ":" & txtMinute.Value 更改为 sDate = myDate.Value & " " & format(txtHour.Value."00") & ":" & format(txtMinute.Value,"00")
    【解决方案2】:

    这是最干净的方法。不需要字符串连接。

    Dim d As Date
    d = CDate(myDate.Value) + TimeSerial(txtHour.Value, txtMinute.Value, 0)
    Range("A1") = d
    Range("A1").NumberFormat = "mm/dd/yyyy hh:mm"
    
    ' If you *really* need the date as a string (which is rarely the case):
    Dim s As String
    s = Format(d, "mm/dd/yyyy hh:mm")
    

    唯一的弱点是CDate(myDate.Value)。来自 VBA 文档:

    CDate 根据系统的区域设置识别日期格式。如果提供的格式不是已识别的日期设置之一,则可能无法确定正确的日、月和年顺序。

    例如,如果用户决定以dd/mm/yyyy 格式输入日期,而不是myDate 中的mm/dd/yyyy,那么它将无法正常工作。请注意,Zaider 的解决方案也有类似的弱点。

    【讨论】:

    • 感谢您的提示。 TimeSerial 对我来说是新的。谢谢。
    猜你喜欢
    • 1970-01-01
    • 2015-12-23
    • 1970-01-01
    • 1970-01-01
    • 2021-10-20
    • 1970-01-01
    • 2021-12-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多