通过 Word VBA 获取两个日期或时间之间差异的 2 种快速方法

立即分享:

在本文中,我们想向您介绍 2 种快速有效的方法,通过 Word 宏获取 2 个特定日期或时间之间的差异。

计算两个具体日期或时间之间剩余的天数或时间并不困难。 您可以自己计算,也可以获取日期或持续时间计算器。 在这里,我们想向您展示 2 种宏方法,使您能够在 Word 中获取日期或时间差异。 以下是详细步骤:

获取日期差异

  1. 首先,打开 Word。
  2. 如果已经激活,则单击“开发人员”选项卡。
  3. 接下来,单击“Visual Basic”打开 VBA 编辑器。 你可以参考 如何将背景音乐插入 Word 文档 将“开发人员”添加到功能区。 或者,如果您不愿意,也可以按“Alt+F11”。点击“开发者”->点击“Visual Basic”
  4. 现在单击“正常”,然后单击“插入”。
  5. 在列表菜单上,选择“模块”。点击“普通”->点击“插入”->点击“模块”
  6. 接下来,双击新模块进入编辑区。
  7. 粘贴以下代码:
Sub CalculateDateDifference()
  Dim dtStartDate As Date
  Dim dtEndDate As Date
  Dim lDaysLeft As Long

  '  Input the start date and end date, calculate the date difference.
  dtStartDate = InputBox("Enter the start date","Start Date","For example:2017/1/1")
  dtEndDate = InputBox("Enter the end date","End Date","For example:2017/2/1")
  lDaysLeft = DateDiff("d", dtStartDate, dtEndDate)

  '  Output the calculate the date difference between the two dates. 
  MsgBox ("There are " & lDaysLeft & " days left from " & dtStartDate & " to " & dtEndDate & vbCrLf)
End Sub
  1. 单击“运行”以运行代码。粘贴代码->点击“运行”
  2. 现在您会看到一个“开始日期”对话框。在文本框中输入开始日期,然后单击“确定”。输入开始日期->点击“确定”
  3. 接下来是“结束日期”对话框。 同样,输入结束日期并单击“确定”。输入结束日期->单击“确定”
  4. 然后会弹出一个消息框,指出两个日期之间的差异。显示日期差异的消息框

如果您需要将结果插入到您的文档中,您可以通过更改代码行“MsgBox(“从“" & dtStartDate & " 到“" & dtEndDate & vbCrLf,还剩下" & lDaysLeft & "天”)“要”Selection.Text = “从“ & dtStartDate & ”到“ & dtEndDate”还剩下“ & lDaysLeft & ”天” & vbCrLf。

获取时差

  1. 首先重复上面的前 6 个步骤。
  2. 然后粘贴这些代码:
Sub CalculateTimeDifference()
  Dim dtStartTime As Date
  Dim dtEndTime As Date
  Dim lTimeLeft As Long
  Dim lHour As Long
  Dim lMinute As Long
  Dim lSecond As Long
 
  '  Get the start time and the end time.
  dtStartTime = InputBox("Enter the start time","Start Time", "For example:18:00:00") 
  dtEndTime = InputBox("Enter the end time","End Time", "For example:18:00:00") 
  '  Calculate the time difference. 
  lTimeLeft = DateDiff("s", dtStartTime, dtEndTime)
  lHour = lTimeLeft \ 3600
  lTimeLeft = lTimeLeft - lHour * 3600
  lMinute = lTimeLeft \ 60
  lSecond = lTimeLeft - lMinute * 60
 
  MsgBox ("There are " & lHour & " hours " & lMinute & " minutes " & lSecond & " seconds left from " & dtStartTime & " to " & dtEndTime & vbCrLf)
End Sub
  1. 记得点击“运行”。粘贴代码->点击“运行”
  2. 在“开始时间”框中,输入开始时间,例如“18:00:00”。输入开始时间->点击“确定”
  3. 然后在“结束时间”对话框中输入结束时间并单击“确定”。 您可以在出现的消息框中查看结果。输入结束时间->单击“确定”时差

降低文件丢失风险

Word 有时会突然停止工作,使我们的文件处于极大的危险之中。 因此,为减少文件损坏的机会,我们建议您定期进行备份。 另外,得到一个 Word文件恢复产品 当您发现自己需要修复损坏的文件时,这是必要的。

作者简介:

Vera Chen 是一位数据恢复专家 DataNumen, Inc.,它是数据恢复技术领域的世界领先者,包括 Excel xls数据修复工具 和 pdf 修复软件产品。 欲了解更多信息,请访问 datanumen.com

立即分享:

评论被关闭。