#1
|
|||
|
|||
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 |
#2
|
|||
|
|||
Why are you doing this through vba rather than through an IF Field in the document itself?
You can test on a DocVariable field. You can also use Document Property Content Controls. Repeating Data Using Document Properties Content Controls and Other Mapped Content Controls |
#3
|
|||
|
|||
Thanks for the reply.
I'm doing it for my own amusement to see if it can be done - for which I created this very simple routine which kind of proves it can... Sub BookmarkUpdate() Dim BMRange As Range 'Identify current Bookmark range and insert text For n = 1 To 4 Set BMRange = ActiveDocument.Bookmarks("MyBookmark").Range If n = 1 Then BMRange.Text = "First" ElseIf n = 2 Then BMRange.Text = "Second" ElseIf n = 3 Then BMRange.Text = "Third" ElseIf n = 4 Then BMRange.Text = "" End If 'Re-insert the bookmark ActiveDocument.Bookmarks.Add "MyBookmark", BMRange Next n End Sub This is more about me trying to understand VBA than actually achieving an end result - but thanks for the link - I don't know what any of it means so something else to learn ;-) |
#4
|
|||
|
|||
Good to see you wan to learn. When you have rather convoluted If ... Else ... End If conditions, it is often easier to use Select Case. Also, if you are going to declare one variable, you might as well declare all.
Code:
Sub BookmarkUpdate() Dim oBMRng As Range Dim lngIndex As Long For lngIndex = 1 To 4 Set oBMRng = ActiveDocument.Bookmarks("MyBookmark").Range Select Case lngIndex Case 1: oBMRng.Text = "First" Case 2: oBMRng.Text = "Second" Case 3: oBMRng.Text = "Third" Case 4: oBMRng.Text = "" End Select 'Re-insert the bookmark ActiveDocument.Bookmarks.Add "MyBookmark", oBMRng Next lngIndex lbl_Exit: Exit Sub End Sub |
#5
|
|||
|
|||
Thanks Greg. This has been a great help to me. I can see what you did and it's easy to follow.
Following on, using your advice, I declared another variable BMcnt and used this as a counter to add on to the bookmark name. This means if I have four bookmarks, I can consecutively cycle through each and change the text in each one. This may not sound very productive but helps me understand For Next loops. I see now that instead of just cycling through, by using IF statements I can write predetermined text to a document via a bookmark, based on a condition. Can you explain the relevance of 'lbl_Exit:' towards the end of the routine? Sub BookmarkUpdate() Dim oBMRng As Range Dim lngIndex As Long Dim BMcnt As Long For BMcnt = 1 To 4 For lngIndex = 1 To 4 Set oBMRng = ActiveDocument.Bookmarks("MyBookmark" & BMcnt).Range Select Case lngIndex Case 1: oBMRng.Text = "First" Case 2: oBMRng.Text = "Second" Case 3: oBMRng.Text = "Third" Case 4: oBMRng.Text = "" End Select 'Re-insert the bookmark ActiveDocument.Bookmarks.Add "MyBookmark" & BMcnt, oBMRng Next lngIndex Next BMcnt lbl_Exit: Exit Sub End Sub |
#6
|
|||
|
|||
Red,
There you go. In the example I provided, lbl_Exit really has no relevance and it is there only as part of my standard coding style (I never like to hit the End Sub line) as an exit point. In practice, it serves as a resume label in error handling. Consider one of the bookmarks is missing: Code:
Sub BookmarkUpdate() Dim oBMRng As Range Dim lngIndex As Long Dim BMcnt As Long On Error GoTo ErrHandler For BMcnt = 1 To 4 For lngIndex = 1 To 4 Set oBMRng = ActiveDocument.Bookmarks("MyBookmark" & BMcnt).Range Select Case lngIndex Case 1: oBMRng.Text = "First" Case 2: oBMRng.Text = "Second" Case 3: oBMRng.Text = "Third" Case 4: oBMRng.Text = "" End Select 'Re-insert the bookmark ActiveDocument.Bookmarks.Add "MyBookmark" & BMcnt, oBMRng Next lngIndex Next BMcnt lbl_Exit: Exit Sub ErrHandler: MsgBox "Bookmark MyBookmark " & BMcnt & " does not exist." Resume lbl_Exit End Sub |
#7
|
||||
|
||||
As a learning experience, creating loops is a useful skill but your examples are not saving a great deal of code. The outer/inner loops don't do anything other than ensuring the actual inside code is run 4 times to do something that only requires a single pass. An example to make use of both loops would be to include both in the bookmark name eg
Set oBMRng = ActiveDocument.Bookmarks("MyBookmark" & BMcnt & lngIndex).Range Another technique worth learning that could be applied to this problem is to call a function and pass values in to the function. I haven't used the loop and Select Case because you are doing something different for each of the loop values. This code also shows how to avoid an error if a bookmark doesn't exist. Code:
Sub BookmarkUpdate2() ResetBookmarks sName:="MyBookmark1", sValue:="First" ResetBookmarks sName:="MyBookmark2", sValue:="Second" ResetBookmarks sName:="MyBookmark3", sValue:="Third" ResetBookmarks sName:="MyBookmark4", sValue:="" End Sub Function ResetBookmarks(sName As String, sValue As String) Dim oRng As Range With ActiveDocument If .Bookmarks.Exists(sName) Then Set oRng = .Bookmarks(sName) oRng.Text = sValue .Bookmarks.Add sName, oRng Else MsgBox "Bookmark does not exist: " & sName End If End With End Function
__________________
Andrew Lockton Chrysalis Design, Melbourne Australia |
#8
|
|||
|
|||
Thanks very much for your input. It is really appreciated
However when I run your sub, I get an error at Set oRng = .Bookmarks(sName) that states: Runtime Error 13: Type mismatch Any ideas? Thanks |
#9
|
||||
|
||||
I missed adding .Range on the end of that line. Try altering it to read
Set oRng = .Bookmarks(sName).Range
__________________
Andrew Lockton Chrysalis Design, Melbourne Australia |
#10
|
|||
|
|||
I've been playing around some more with this and rather than just inserting text sequentially into bookmarks I've trying to insert specific text into bookmarks based on particular criteria. In this case selecting pre written text in the form of bookmarks to produce a document tailored to whether the recipient status is either " Single", "Pair 1 or "Pair 2"
This seems to work OK for my learning needs but wondered if there was a more efficient way of writing the code because I'm guessing the way I have written it is probably not very elegant and would lead you to suspect I was 5 years old Sub BookmarkUpdate2() Dim oBMRng As Range Dim lngIndex As Long Dim BMcnt As Long Dim Status As String Dim z As Long Dim x As Long For BMcnt = 1 To 4 'Loop through Bookmarks x = 1 'Change to simulate Status either 1 = Single. 2 = Pair 1 or 3 =Pair 2 If x = 1 Then Status = "Single" If x = 2 Then Status = "Pair 1" If x = 3 Then Status = "Pair 2" If BMcnt = 1 And Status = "Single" Then z = 1 ElseIf BMcnt = 1 And Status <> "Single" Then z = 2 ElseIf BMcnt = 2 And Status <> "Pair 2" Then z = 3 ElseIf BMcnt = 2 And Status = "Pair 2" Then z = 4 ElseIf BMcnt = 3 And Status = "Single" Then z = 8 ElseIf BMcnt = 3 And Status <> "Single" Then z = 5 ElseIf BMcnt = 4 And Status <> "Pair 1" Then z = 6 ElseIf BMcnt = 4 And Status = "Pair 1" Then z = 7 End If lngIndex = z Set oBMRng = ActiveDocument.Bookmarks("MyBookmark" & BMcnt).Range Select Case lngIndex Case 1: oBMRng.Text = "You have been assigned to Team <<TeamNo>>. Usually you would be paired with another team, however at this time no suitable pairing has been identified" Case 2: oBMRng.Text = "You have been assigned to Team <<TeamNo >> and paired with: <<PairedWithTeam>>." & vbNewLine & "Their contact details are as follows: " & vbNewLine & "<<TheirName>>" & vbNewLine & "<<TheirPhone>>" & vbNewLine & "<<TheirEmail>>" Case 3: oBMRng.Text = "The equipment will be delivered to <<YourTeam>> on <<DeliveryDate>>." Case 4: oBMRng.Text = "The equipment will be delivered to <<PairedWithTeam>> on <<DeliveryDate>>." Case 5: oBMRng.Text = "The equipment is then exchanged between yourselves and <<PairedWithTeam>> on alternate weeks over a 6-week period." Case 6: oBMRng.Text = "The equipment will then be collected from <<YourTeam>> on <<CollectionDate>>." Case 7: oBMRng.Text = "The equipment will then be collected from <<PairedWithTeam>> on <<CollectionDate>>." Case 8: oBMRng.Text = "" End Select 'Re-insert the bookmark ActiveDocument.Bookmarks.Add "MyBookmark" & BMcnt, oBMRng 'Next lngIndex Next BMcnt lbl_Exit: Exit Sub End Sub Last edited by RedZed1100; 08-26-2020 at 06:08 AM. Reason: Typing errors |
#11
|
|||
|
|||
Thanks. It wasn't obvious -not to me anyway.
|
#12
|
||||
|
||||
RedZed
As the saying goes "To a man with a hammer, every problem looks like a nail" To put it another way, just because you know how to use a For loop doesn't make it right for every task. Study the code I provided and step through it to understand what it is doing. Then use that structure to see if you can apply it to your problem without a need for a loop.
__________________
Andrew Lockton Chrysalis Design, Melbourne Australia |
|
Similar Threads | ||||
Thread | Thread Starter | Forum | Replies | Last Post |
Replacing text held in all bookmarks | THH4929 | Word VBA | 6 | 06-02-2018 04:29 AM |
How to insert bookmarks for content or Text of ContentControl | lvganesh | Word VBA | 5 | 12-12-2017 11:27 PM |
Deleting only all bookmarks contents not the bookmarks | adilprodigy | Word VBA | 1 | 10-11-2017 01:31 PM |
Macro to hide/unhide text to call variable bookmarks | Dr. Z | Word VBA | 2 | 05-27-2017 08:20 PM |
Form updating Bookmarks - writes to the bookmarks multiple times | PeterPlys | Word VBA | 13 | 01-14-2015 06:41 AM |