date和时间使用VBA Excel更改24小时

如何在24小时内为此macros添加时间我已经创build了? 下面是macros。 我需要添加一个时间戳,我不知道如何。

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小时的时间来增加这个工作表的macros。 我有一个我需要做的例子。 在这个例子中,date和时间显示我需要时间在24小时内增加。

在这里输入图像说明

首先,我build议始终使用Option Explicit。 工具>选项>编辑器(选项卡)>需要variables声明(checkbox),可以在未来的项目中通过MS VB窗口中的菜单启用。

现在到企业:如果你想要一个范围(在这个例子中是B2:B25和C2:C25)以1小时的增量填充date+时间,我推荐使用类似下面的内容:

 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 

正如你所说,你从一个date开始,因此我从一个date(没有时间)在InputBox开始。

现在,如果您只想在有限的时间内重复这个操作,您可以通过限制它适用的范围(在这种情况下是B2:B25)来实现,当到达底部时,循环将停止。

现在它会自动填充C列,date时间为将来24小时,如果您希望将来有date,请跳过C列的行中的Timeserial部分。 如果您希望将来1小时,则将该行更改为:

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