在Excel中添加x个date与vba的date

我打算用一个popup框将x天添加到长date。

Public Function AskForDeadlinePlus4() As String Dim strUserResponse As String strUserResponse = InputBox("Enter Validuntil Date: Add # of Days To Survey end date") strUserResponse = FormatDateTime(strUserResponse + I2, vbLongDate) ActiveSheet.Cells(2, 10).Value = strUserResponse 'the 2, 10 is the cell reference for J2 - row 2, column 10. End Function 

单元格I2中的调查结束date。

当我运行这个我得到(谷歌如何做到这一点我很累)

4 + I2I2 = Friday, April 05, 2013>> Wednesday, January 03, 1900

当然,我需要Tuesday, April 09, 2013

谢谢

你使用了DateAdd函数吗?

 Sub DateExample() Dim strUserResponse As String '## capture the user input' Dim myDate As Date '## the date you want to add to' Dim numDays As Double '## The number of days you want to add' strUserResponse = InputBox("Enter Validuntil Date: Add # of Days To Survey end date") numDays = InputBox("How many days to add?") myDate = CDate(strUserResponse) MsgBox DateAdd("d", numDays, myDate) End Sub 

我认为这个代码就是你在使用DateAdd(<base eg Day = "D">, <number>, <date>)函数后的结果:

 Public Function AskForDeadlinePlus4() As String Dim strUserResponse As Date, iNumber As Long, rResponse As Variant AskForDeadlinePlus4 = "" 'set default value iNumber = CLng([I2]) rResponse = InputBox("Enter Validuntil Date: Add " & iNumber & " Day(s) To Survey end date") If rResponse = False Then 'no value entered Exit Function ElseIf Not IsDate(rResponse) Then 'no date entered Exit Function Else 'valid date entered strUserResponse = DateAdd("D", iNumber, CDate(rResponse)) End If AskForDeadlinePlus4 = FormatDateTime(strUserResponse, vbLongDate) End Function 

只是几点:

  • 如果没有inputinput,input函数将返回布尔值FALSE
  • 你上面使用的testing是一个函数,使用时会返回一个值
  • 如果你想在另一个VBA代码中使用, i = AskForDeadlinePlus4是它的用法;
  • 但是你也可以在一个单元格中使用它,但是只有在每次计算时都必须这样做,这将提示一个input,并为每个单元格input一个单元格=AskForDeadlinePlus4 ; 和
  • 另外我已经添加了一个检查,看看是否inputdate,因为用户可能不会input一个有效的。

如果你想在VBA中使用:

 Sub GetInfo() 'the 2, 10 is the cell reference for J2 - row 2, column 10. ActiveSheet.Cells(2, 10).Value = AskForDeadlinePlus4 End Sub 

而不是使用需要更多input的DateAdd,也可以使用DateValue。 以下将做到这一点。

 DateValue(strUserResponse )+I2 

另一个解决scheme是使用转换函数CDate。

 CDate(strUserResponse )+I2