none
How to make a calculation with the Date Picker Content Control in Word RRS feed

  • Question

  • Hello

    I'd like to be able to select two dates with two Date Picker content controls and then produce the resultant number of nights. For example after choosing 03/03/2109 and 03/05/2109 in a separate field it produces (2 nights) but also after choosing 03/03/2109 and 03/04/2109 it produces (1 night).

    Any help much appreciated

    Kate

    Wednesday, April 11, 2018 8:43 AM

All replies

  • Assuming the date fields have the tags - DateTo and DateFrom and the number of nights field has the tag Nights then the following should be close. You can add more error handling as required.

    You might find https://www.gmayor.com/insert_content_control_addin.htm useful

    Sub CountDays()
    Dim DateFrom As Date, DateTo As Date
    Dim iNights As Integer
        If ActiveDocument.SelectContentControlsByTag("DateFrom").Item(1).ShowingPlaceholderText = False And _
           ActiveDocument.SelectContentControlsByTag("DateTo").Item(1).ShowingPlaceholderText = False Then
            DateFrom = CDate(ActiveDocument.SelectContentControlsByTag("DateFrom").Item(1).Range.Text)
            DateTo = CDate(ActiveDocument.SelectContentControlsByTag("DateTo").Item(1).Range.Text)
            iNights = CInt(DateTo - DateFrom)
            ActiveDocument.SelectContentControlsByTag("Nights").Item(1).Range.Text = CStr(iNights)
        End If
    lbl_Exit:
        Exit Sub
    End Sub

    You could automate this with the aid of a pair of macros in the ThisDocument module of the Document project

    Private Sub Document_ContentControlOnEnter(ByVal ContentControl As ContentControl)
        Select Case ContentControl.Tag
            Case "DateFrom", "DateTo", "Nights"
                CountDays
            Case Else
        End Select
    lbl_Exit:
        Exit Sub
    End Sub
    
    Private Sub Document_ContentControlOnExit(ByVal ContentControl As ContentControl, Cancel As Boolean)
        Select Case ContentControl.Tag
            Case "DateFrom", "DateTo", "Nights"
                CountDays
            Case Else
        End Select
    lbl_Exit:
        Exit Sub
    End Sub
    
    Thus if the two dates are filled and the three tagged fields exist, the macro will run each time you enter or leave one of the fields.


    Graham Mayor - Word MVP
    www.gmayor.com


    Wednesday, April 11, 2018 9:11 AM