Add x number of days to a date with vba in excel

后端 未结 3 1226
时光说笑
时光说笑 2020-12-19 07:38

I am tring to add x number of days to a Long date with a pop up box.

Public Function AskForDeadlinePlus4() As String
    Dim strUserResponse As String

    s         


        
相关标签:
3条回答
  • 2020-12-19 07:45

    Have you used the DateAdd function?

    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
    
    0 讨论(0)
  • 2020-12-19 07:52

    I think this code is what your after using the DateAdd(<base e.g. Day = "D">, <number>, <date>) function:

    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
    

    Just a few points though:

    • The input function will return the Boolean FALSE if no input is entered.
    • The test you used above is a function and will return a value when used
    • If you want to use in in another VBA code, i = AskForDeadlinePlus4 is its usage;
    • But you can also use it in a cell but only when necessary as with every calculation this will prompt an input and for every cell its in, =AskForDeadlinePlus4; and
    • Plus I've added a check to see if a date was entered as the user may not enter a valid one.

    If you want to use in VBA:

    Sub GetInfo()
        'the 2, 10 is the cell reference for J2 - row 2, column 10.
        ActiveSheet.Cells(2, 10).Value = AskForDeadlinePlus4
    End Sub
    
    0 讨论(0)
  • 2020-12-19 08:09

    Instead of using DateAdd, which requires more typing, you could also use DateValue. Following would do it.

    DateValue(strUserResponse )+I2
    

    Another solution would be using the conversion function, CDate.

    CDate(strUserResponse )+I2
    
    0 讨论(0)
提交回复
热议问题