View Single Post
 
Old 08-22-2020, 10:05 AM
RedZed1100 RedZed1100 is offline Windows 10 Office 2016
Novice
 
Join Date: Aug 2020
Location: England
Posts: 8
RedZed1100 is on a distinguished road
Default Using If Then with Bookmarks to specify text

Hi

I'm new to vba so please go easy on me ;-)

My goal is to show different text (or none at all) in a word document based on a variable.

I've been playing around with bookmarks and came across some interesting VBA code shown below to write content to bookmarks without destroying them, on a different site (Greg Maxey - The Anchorage). Whilst I have to admit I don't understand most of it I was intrigued by this which allows a user to manually update bookmarks:
This got me thinking if it is possible to update the contents of bookmarks depending on the out come of an If statement?


ie If [Status] = 1 then "Write this text" to Bookmark x otherwise "Write some other text"
If [Status] = 2 then "Write this text" to Bookmark x otherwise "Clear the bookmark"
That sort of thing...

Unfortunately I'm not sure how start to write this in vba and wonder if someone could assist me - if it's actually possible to do?

If anyone could give me a start that would be great!

Many thanks

RedZed



Original code by Greg Maxey - The Anchorage which inspired my questionn:


Sub DemoWriteToBookmarkRange()
Dim strInput As String
strInput = InputBox("What is your favorite color?")
WriteToBookmarkRange ActiveDocument, "bmInBookmark", strInput
strInput = InputBox("What is your favorite food?")
WriteToBookmarkRange ActiveDocument, "bmInBookmarkFood", strInput
strInput = InputBox("What is your favorite soft drink?")
WriteToBookmarkRange ActiveDocument, "bmInBookmarkDrink", strInput
lbl_Exit:
Exit Sub
End Sub

Sub WriteToBookmarkRange(ByRef oDoc As Document, bmName As String, strContent As String)
Dim oRng As Word.Range
If oDoc.Bookmarks.Exists(bmName) Then
Set oRng = oDoc.Bookmarks(bmName).Range
oRng.Text = strContent
oDoc.Bookmarks.Add bmName, oRng
Else
MsgBox "An error occurred while processing your document." _
& vbCr & "The bookmark " & Chr(34) + bmName + Chr(34) & " does not exist.", _
vbInformation, "Missing Bookmark"
End If
lbl_Exit:
Exit Sub
End Sub
Reply With Quote