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

后端 未结 3 1227
时光说笑
时光说笑 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:52

    I think this code is what your after using the DateAdd(, , ) 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
    

提交回复
热议问题