我想通过一个弹出框将x天数添加到一个长日期。
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中。
当我跑步时,我得到(谷歌搜索如何做到这一点,我很累)
4 + I2
(其中I2 = Friday, April 05, 2013
)>> Wednesday, January 03, 1900
当然我需要Tuesday, April 09, 2013
由于
答案 0 :(得分:16)
您是否使用过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
答案 1 :(得分:2)
我认为此代码是您使用DateAdd(<base e.g. 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
但只有几点:
i = AskForDeadlinePlus4
是其用法; =AskForDeadlinePlus4
;和如果您想在VBA中使用:
Sub GetInfo()
'the 2, 10 is the cell reference for J2 - row 2, column 10.
ActiveSheet.Cells(2, 10).Value = AskForDeadlinePlus4
End Sub
答案 2 :(得分:0)
您可以使用DateValue,而不是使用需要更多输入的DateAdd。以下会这样做。
DateValue(strUserResponse )+I2
另一种解决方案是使用转换函数CDate。
CDate(strUserResponse )+I2