so I started with VBA yesterday and keep running into walls. In the long run, I'm trying to create a Word template that checks if it's still up to date or if it's time for revision.
Right now I want to store a date from the document in a variable. I couldn't find a method to directly read out something in date format so now I'm using Selection.Text and CDate but that gives me an error (incompatible types) because my selection seems to contain another character or marker ([]). I'm guessing it has something to do with the fact that the bookmark is on a cell of a table within my Word document because it works fine in the running text.
I'm doing this in a table because this way I can be sure where the date in question is in the document and because I'm not sure how to reset the bookmark after the date has been changed.
I tried to limit the selection to the date by using Selection.SetRange Start:=0, End:=8 (and a few variations) but that selects only a space and the ominous marker (or another cell entirely).
I have also looked into Ranges but as far as I can tell it doesn't solve my problem and I can't really use them yet, so for now I'm sticking to selection.
This is my code:
Sub ChangeNextRev()
Dim nextRevision As Date
Dim RevisionDate As Date
Dim temp As String
'Selection.GoTo what:=wdGoToBookmark, Name:="lastRevision"
'Selection.SetRange Start:=0, End:=8
'Selection.GoTo what:=wdGoToBookmark, Name:="lastRevision"
Selection.GoTo what:=wdGoToBookmark, Name:="runningText"
temp = Selection.Text
RevisionDate = CDate(temp)
Debug.Print (RevisionDate)
nextRevision = RevisionDate + 14
With Selection
.GoTo what:=wdGoToBookmark, Name:="nextRevision"
.TypeText Text:=Format$(nextRevision, "DD.MM.YY")
End With
End Sub
Can someone point me in the right direction? How can I only select the date I need? Is there an easier way besides a table to control where the date is entered or to find it afterwards? Any help on where I'm going wrong would be greatly appreciated :)
Your guess about the table cell is correct, but you can work around that by trimming off the extraneous character(s). End-of-cell is a Chr(13) + Chr(7) (Word paragraph plus cell structure marker).
There are various ways to code this, but I have the following function at-hand:
'Your code, relevant lines, slightly altered:
Selection.GoTo what:=wdGoToBookmark, Name:="runningText"
temp = TrimCellText(Selection.Text)
RevisionDate = CDate(temp)
Debug.Print (RevisionDate)
'Function to return string without end-of-cell characters
Function TrimCellText(s As String) As String
Do While Len(s) > 0 And (Right(s, 1) = Chr(13) Or Right(s, 1) = Chr(7))
s = Left(s, Len(s) - 1)
Loop
TrimCellText = s
End Function