在Visual Basic / Excel中处理date

使用Visual Basic / Excel非常新。 我正在尝试编写一个快速脚本,将当前时间input到一列,并允许用户input多less天/小时/分钟,直到新的时间,然后输出到另一列。

我相信这不是最好的办法,但我到目前为止是以下几点。 我已经放弃了与date摆弄,只是与时间工作:

Sub TimeModule() Dim DaysLeft, HoursLeft, MinutesLeft As Double DaysLeft = Val(InputBox("Days left")) HoursLeft = Val(InputBox("Hours left")) MinutesLeft = Val(InputBox("Minutes left")) Dim CurrentTime As Date CurrentTime = TimeValue(Now()) ActiveCell.Value = CurrentTime ActiveCell.Offset(0, 1) = CurrentTime + Time(HoursLeft, MinutesLeft, 0) End Sub 

当然,我得到一个错误。 如果任何人都可以通过更好的方式来解决这个问题,那么随着我误用的function,我将非常感激!

编辑:我当然最终会喜欢脚本来处理日子。

我认为这是可能的,只要在Excel中使用单元格函数,如果我已经正确地理解了你。

例如,这是你会看到…

 Time Now: Days: Hours: Minutes: New Time: 30/05/2012 23:34 15 6 23 15/06/2012 05:57 

…这是什么在每个单元格(假设左上angular的单元格是A1)…

 Time Now: Days: Hours: Minutes: New Time: =NOW() 15 6 23 =A2+B2+TIME(C2,D2,0) 

描述每个function:

  • NOW()返回格式化为date和时间的当前date和时间。
  • DATE(year,month,day)返回表示MS Exceldate – 时间代码中的date的数字。
  • TIME(hours,minutes,seconds)将以数字forms给出的小时,分​​钟和秒数转换为Excel序列号,并使用时间格式进行格式化。

parsing最后一个单元格中的方程:

  • A2是包含当前date/时间的单元格(截至上次工作表计算)。
  • B2是天的用户input值。
  • TIME(C2,D2,0)是TIME()函数,分别从单元格C2D2获取用户input的小时和分钟值。

这是否就像你想要的function…?

如果你想使用VBA,你的代码唯一的问题是“时间”function。 你可以使用CDate来代替:

 Sub TimeModule() Dim DaysLeft, HoursLeft, MinutesLeft As Double DaysLeft = Val(InputBox("Days left")) HoursLeft = Val(InputBox("Hours left")) MinutesLeft = Val(InputBox("Minutes left")) Dim CurrentTime As Date CurrentTime = TimeValue(Now()) ActiveCell.Value = Now() ActiveCell.Offset(0, 1) = ActiveCell.Value + DaysLeft + CDate(HoursLeft & ":" & MinutesLeft) 'ActiveCell.Offset(0, 1) = CurrentTime + Time(HoursLeft, MinutesLeft, 0) End Sub 

当你以这种方式“暗淡”时,你必须logging每个variables的数据types。 你有它的方式MinutesLeft是一个Double,一切(默认)一个Variant。

您正在寻找的时间函数是TimeSerial。

date存储为特定date以来的天数。 要将date添加到date,您可以简单地将这些数字相加。

 Sub TimeModule() Dim lDaysLeft As Long Dim lHoursLeft As Long Dim lMinutesLeft As Double Dim dtCurrent As Date lDaysLeft = Val(InputBox("Days left")) lHoursLeft = Val(InputBox("Hours left")) lMinutesLeft = Val(InputBox("Minutes left")) dtCurrent = Now() ActiveCell.Value = dtCurrent ActiveCell.Offset(0, 1).Value = dtCurrent + lDaysLeft + TimeSerial(lHoursLeft, lMinutesLeft, 0) End Sub