7

我正在尝试使用弹出框将 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

谢谢

4

3 回答 3

17

你用过这个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
于 2013-04-28T03:16:52.797 回答
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

不过只有几点:

  • 如果没有输入,输入函数将返回布尔值FALSE 。
  • 您上面使用的测试是一个函数,使用时会返回一个值
  • 如果要在另一个VBA代码中使用,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
于 2013-04-28T09:01:16.737 回答
0

除了使用需要更多输入的 DateAdd,您还可以使用 DateValue。以下会做到这一点。

DateValue(strUserResponse )+I2

另一种解决方案是使用转换函数 CDate。

CDate(strUserResponse )+I2
于 2017-07-21T11:01:51.303 回答