WORD DATE CALCULATIONS IN A USERFORM

G

Gregory Mettam

I am familiar with the use of StartDate and EndDate fields and I use them
frequently to calculate the number of days between two dates. This is done
by putting the fields into bookmarks and subtracting one bookmark from the
other.

However, I want to do achieve this same result via a Userform. Essentially,
I want to type the StartDate and EndDate into the form and if at all
possible leave the bookmarks intact after pressing the Commandbutton. I
have achieved this with other data on the same form.

The code I am using (most of it borrowed)is set out below.

I hope someone can help.

Greg.

Private Sub ClickToFinish_Click()
Dim oControl As Control
Dim strBM_Name As String
Dim strBM_Text As String

For Each oControl In frmDataInput.Controls
If Left(oControl.Name, 3) = "txt" Then
strBM_Name = Right(oControl.Name, Len(oControl.Name) - 3)
strBM_Text = frmDataInput.Controls(oControl.Name).Text
Call FillABookmark(strBM_Name, strBM_Text)
End If
Next
ActiveDocument.Fields.Update
Unload Me

End Sub

Option Explicit


Sub FillABookmark(strBM_Name As String, strBM_Text As String)
Dim ThisDoc As Word.Document
Set ThisDoc = ActiveDocument
' following is for formfields, if no formfields can remove
If ThisDoc.ProtectionType = wdAllowOnlyFormFields Then
ThisDoc.Unprotect
End If
On Error Resume Next
With Selection
.GoTo what:=wdGoToBookmark, Name:=strBM_Name
.Collapse Direction:=wdCollapseEnd
ThisDoc.Bookmarks(strBM_Name).Range.Text = strBM_Text
.MoveEnd unit:=wdCharacter, Count:=Len(strBM_Text)
ThisDoc.Bookmarks.Add Name:=strBM_Name, Range:=Selection.Range
.Collapse Direction:=wdCollapseEnd
End With
' to reset formfields
If ThisDoc.FormFields.Count > 0 Then
ThisDoc.Protect wdAllowOnlyFormFields, Password:=""
End If
Set ThisDoc = Nothing
End Sub

Sub DemoForm()
frmDataInput.Show
End Sub
 
A

aidan.heritage

not sure what you want to know, BUT

DateValue(TextBox1.Text) - DateValue(TextBox2.Text)

would give you the number of days between two dates - you would need to
validate the inputs on the textboxes to ensure they were entered as
dates though!
 
D

Doug Robbins - Word MVP

Use the DateDiff() function

--
Hope this helps.

Please reply to the newsgroup unless you wish to avail yourself of my
services on a paid consulting basis.

Doug Robbins - Word MVP
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top