繁体   English   中英

使用VBA Excel 24小时更改日期和时间

[英]Date and Time Change 24 hours with VBA Excel

如何在24小时内向已经创建的宏添加时间? 这是下面的宏。 我需要为其添加时间戳,但不确定如何。

Private Sub Workbook_Open()

Dim dtDate As Date

dtDate = InputBox("Date", , Date)

Set SelRange = Range("B:B")
For Each b In SelRange.Rows
b.Value = dtDate
b.Offset(0, 1).Value = dtDate + 1
Next
End Sub

我需要一些时间来像该工作表的宏一样增加24小时。 我有一个我需要做的事的例子。 在此示例中,日期和时间显示我需要时间在24小时内增加。

在此处输入图片说明

首先,我建议始终使用Option Explicit。 可以通过MS VB窗口中的菜单为将来的项目启用此功能:工具>选项>编辑器(选项卡)>需要变量声明(复选框)

现在开始营业:如果您希望一个范围(在此示例中为B2:B25和C2:C25)以日期+时间(以1小时为增量)填充,我建议使用以下内容:

Option Explicit

Private Sub Workbook_Open()

    Dim SelRange As Range
    Dim b As Range
    Dim dtDate As Date
    Dim intHours As Long

    'Enter the starting date and time
    dtDate = InputBox("Start date", , Date)

    'Initate our hours counter
    intHours = 0

    'Assign a worksheet range for our date-time range
    Set SelRange = Range("B2:B25")


    'Write the date-time range with 1 hour increments
    For Each b In SelRange
        b.Value2 = dtDate + TimeSerial(intHours, 0, 0)
        '24 hours later in the cell to the right of this
        b.Offset(0, 1).Value2 = dtDate + 1 + TimeSerial(intHours, 0, 0)
        intHours = intHours + 1
        'To avoid an overflow in the TimeSerial function the intHours are keps smaller than then Integer maximum
        If intHours > 24 Then
            intHours = intHours - 24
            dtDate = dtDate + 1
        End If
    Next

End Sub

正如您提到的,您从日期开始,因此我在InputBox中以日期(无时间)开始。

现在,如果您希望仅重复有限的时间,则可以通过限制其适用范围(在这种情况下为B2:B25)来做到这一点,循环将在到达底部时停止。

现在,它会自动以将来24小时的日期时间填充C列,如果您只希望它具有将来的日期,则跳过C列行中的Timeserial部分。 如果您希望将其设置为将来的1小时,则将行更改为:

b.Offset(0, 1).Value2 = dtDate + TimeSerial(intHours +1, 0, 0)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM