PDA

View Full Version : Check for text within a bookmark



Roderick
10-10-2018, 03:04 PM
I have a number of bookmarks which enclose either a blank space or a field. I now want to check whether, when a bookmark is selected which of the two it contains.

This is the code I have at the moment:

Dim oRng As Word.Range
ActiveDocument.Bookmarks("ContentsFigures").Range.Select

If Len(ActiveDocument.Bookmarks("ContentsFigures").Range.Text) = 0 Then
MsgBox "No text in the bookmark"
Else
MsgBox "The bookmark holds text"
End If
When I run the procedure it always tells me that the bookmark contains text irrespective of which type it holds.

Where am I going wrong, please?

Roderick

macropod
10-10-2018, 07:43 PM
Your code can only be returning a non-0 value for the bookmark text's length if the bookmark actually spans some text (even a space).

PS: the first two code lines in your post serve no purpose in this context.

gmayor
10-11-2018, 12:37 AM
You could call a function or a pair of functions to determine what is in a named control.


Sub Macro1()
If BMTextTest("ContentsFigures") = True Then
MsgBox "The bookmark holds text"
Else
MsgBox "No text in the bookmark"
End If

If BMFieldTest("ContentsFigures") = True Then
MsgBox "The bookmark contains a field"
Else
MsgBox "No field in the bookmark"
End If
End Sub

Function BMTextTest(strBM As String) As Boolean
BMTextTest = False
If Len(Trim(ActiveDocument.Bookmarks(strBM).Range.Text)) > 0 Then
BMTextTest = True
End If
End Function

Function BMFieldTest(strBM As String) As Boolean
BMFieldTest = False
If ActiveDocument.Bookmarks(strBM).Range.Fields.Count > 0 Then
BMFieldTest = True
End If
End Function

Roderick
10-11-2018, 02:21 PM
Thanks, Paul.

I see what you mean. I've therefore replaced the "0" in the statement above with a "1" i.e. one space and it works correctly.

Thanks again.

Roderick
10-11-2018, 02:27 PM
Thanks, Graham. Will test this one out as I have a feeling that it will be needed in the future.

Thanks again.

Roderick

gmaxey
10-11-2018, 03:12 PM
Or maybe a combined function:


Sub Macro1()
MsgBox BMTest("ContentsFigures")
End Sub
Function BMTest(strBM As String) As String
Dim oBM As Bookmark
If ActiveDocument.Bookmarks.Exists(strBM) Then
Set oBM = ActiveDocument.Bookmarks(strBM)
Select Case True
Case Asc(oBM.Range.Text) = 32: BMTest = "Bookmark contains a space."
Case oBM.Range.Fields.Count > 0: BMTest = "Bookmark contains a field."
Case Len(oBM.Range.Text) > 0: BMTest = "Bookmark contains text other than a single space."
End Select
Else
BMTest = "Bookmark does not exist."
End If
lbl_Exit:
Exit Function
End Function