Semenalidery.com

IT Новости из мира ПК
2 просмотров
Рейтинг статьи
1 звезда2 звезды3 звезды4 звезды5 звезд
Загрузка...

Bookmarks vba word

Bookmarks vba word

A big difference between Ranges and Bookmarks, when you insert text at the end of a bookmark Word does not expand the Bookmark to include the new text. However when you insert text at the end of a Range, the Range does expand to include the text.

It is possible to replace the bookmark and keep the enclosing bookmark
If the enclosing bookmark contains a paragraph mark, then the text will be replaced.

Two Different Types

The most important thing to remember when working with bookmarks, is that there are two types:

Placeholder Bookmarks — If you click somewhere in a document and insert a bookmark it will look like an I beam.

Enclosing Bookmarks — If you select some text and insert a bookmark it will look like the selected text is enclosed in square brackets.

There are several ways to insert text at (or into) a bookmark.
Which method you use will depend on whether you want to retrieve the text from the bookmark at a later time.
If you want to retrieve the text from a bookmark, then it needs to be an enclosing bookmark.

Displaying the Bookmarks

Always make sure that your bookmarks are visible (Tools > Options)(View tab, «Bookmark»).

Bookmark Objects

Bookmark objects are kept in the Bookmarks collections for the document.

Every bookmark has a range associated with it

This is the general location of the bookmark

Placeholder Bookmarks

If the bookmark is a placeholder bookmark then the Text is inserted after the bookmark.

The text is always inserted after the bookmark regardless of which method you use.

You may want to insert text at a «placeholder» bookmark that can be retrieved at a later time.

Enclosing Bookmarks

If the bookmark is an enclosing bookmark and does not contain and characters then, it will be deleted and the inserted text will appear in its place.

Insert Before — [ Inserted Text Original Text ]

Insert After — [ Original Text ] Inserted Text

You can retrieve the text from an enclosing bookmark using:

You may want to replace the enclosing bookmark with some text (i.e. replacing the bookmark)..
What you need to do is replace the bookmark with the text and then recreate the bookmark around the text.

Problem — Inserting Text at a bookmark deletes it !

The following line of code deletes the bookmark

Using the InsertAfter or InsertBefore method does not work satisfactorily either.
If the bookmark is currently empty then the following line will leave the bookmark at the start of the text, rather than containing it.

And if the bookmark already contains some text then the text is appended to the existing text instead of replacing it.

The best way is to set a range variable to the bookmarks range.

Selecting

This does not work with bookmarks in headers and footers

The default Count is 1.
The default Which is
When you use the GoTo method with any of the following (wdGoToGrammaticalError, wdGoToProofreadingError or wdGoToSpellingError) constants the range that is returned includes any grammar error text or spelling error text

Creating Bookmarks

The Name must be a single word with no spaces

If no range is defined then the current insertion point is used

This creates a bookmark that refers to the same location

Deleting Bookmarks

Inserting Text

Changes the contents of a the bookmark

Got the bookmark, replace the text and keep the bookmark

Add or delete bookmarks in a Word document or Outlook message

A bookmark in Word works like a bookmark you might place in a book: it marks a place that you want to find again easily. You can enter as many bookmarks as you want in your document or Outlook message, and you can give each one a unique name so they’re easy to identify.

To add a bookmark, you first mark the bookmark location in your document. After that, you can jump to the location or add links to it within your document or Outlook message. You can also delete bookmarks from a document or Outlook message.

Bookmark the location

Select text, a picture, or a place in your document where you want to insert a bookmark.

Click Insert > Bookmark.

Under Bookmark name, type a name and click Add.

Note: Bookmark names need to begin with a letter. They can include both numbers and letters, but not spaces. If you need to separate words, you can use an underscore ( _ )—for example, First_heading.

Go to the bookmarked location

After creating your bookmarks, you can add links to them within your document or jump to them at any time.

Читать еще:  Визитки в word

Jump to a bookmark

Type Ctrl+G to open the Go To tab in the Find and Replace box. Under Go to what, click Bookmark. Enter or select the bookmark name, and then click Go To.

Link to a bookmark

You can also add hyperlinks that will take you to a bookmarked location in the same document.

Select the text or object you want to use as a hyperlink.

Right-click and then click Hyperlink .

Under Link to, click Place in This Document.

In the list, select the heading or bookmark that you want to link to.

Note: To customize the Screen Tip that appears when you rest the pointer over the hyperlink, click ScreenTip, and then type the text that you want.

If you’re having any issues or problems with bookmarks, read about the various techniques to troubleshoot bookmarks.

Delete a bookmark

Click Insert > Bookmark.

Click either Name or Location to sort the list of bookmarks in the document.

Click the name of the bookmark you want to delete, and then click Delete.

If you have inserted a hyperlink to the deleted bookmark, right-click the linked text and then click Remove Hyperlink.

Note: To delete both the bookmark and the bookmarked item (such as a block of text or other element), select the item, and then press Delete.

Add or delete bookmarks in a Word document or Outlook message

A bookmark in Word works like a bookmark you might place in a book: it marks a place that you want to find again easily. You can enter as many bookmarks as you want in your document or Outlook message, and you can give each one a unique name so they’re easy to identify.

To add a bookmark, you first mark the bookmark location in your document. After that, you can jump to the location or add links to it within your document or Outlook message. You can also delete bookmarks from a document or Outlook message.

Bookmark the location

Select text, a picture, or a place in your document where you want to insert a bookmark.

Click Insert > Bookmark.

Under Bookmark name, type a name and click Add.

Note: Bookmark names need to begin with a letter. They can include both numbers and letters, but not spaces. If you need to separate words, you can use an underscore ( _ )—for example, First_heading.

Go to the bookmarked location

After creating your bookmarks, you can add links to them within your document or jump to them at any time.

Jump to a bookmark

Type Ctrl+G to open the Go To tab in the Find and Replace box. Under Go to what, click Bookmark. Enter or select the bookmark name, and then click Go To.

Link to a bookmark

You can also add hyperlinks that will take you to a bookmarked location in the same document.

Select the text or object you want to use as a hyperlink.

Right-click and then click Hyperlink .

Under Link to, click Place in This Document.

In the list, select the heading or bookmark that you want to link to.

Note: To customize the Screen Tip that appears when you rest the pointer over the hyperlink, click ScreenTip, and then type the text that you want.

If you’re having any issues or problems with bookmarks, read about the various techniques to troubleshoot bookmarks.

Delete a bookmark

Click Insert > Bookmark.

Click either Name or Location to sort the list of bookmarks in the document.

Click the name of the bookmark you want to delete, and then click Delete.

If you have inserted a hyperlink to the deleted bookmark, right-click the linked text and then click Remove Hyperlink.

Note: To delete both the bookmark and the bookmarked item (such as a block of text or other element), select the item, and then press Delete.

VBA — Word — Bookmarks disappearing when I try to write text on them

I am trying to make a macro in Excel, which takes a sample Word file with some bookmarks on it and writes something on the bookmarks. It works for one bookmark, but for the second, third, etc it simply deletes the other entries.

E.g. after the running of my code, I have only written «Info4». I see Info1, Info2 and Info 3 being written and deleted while the macro is run.

Any ideas? Here comes the code:

Читать еще:  Функции vba word

I have tried to rewrite the bookmarks, once they are deleted, but the success was no different. Thus, waiting for ideas! 😀

Создан 25 май. 16 2016-05-25 08:02:10 Vityata

I couldn’t reproduce this with Office 16.0. Can you clarify what exactly happens? When you set one bookmark text all the others get removed (the text, not the bookmark that is)? Or is just the previously altered text removed? When exactly is it removed? What about other bookmarks in the document that you don’t access via your code? What happens if you skip ‘obj_BMRange’ and set ‘word_obj.activedocument.Bookmarks(«Info2»).Range.Text’ directly? – arcadeprecinct 25 май. 16 2016-05-25 09:36:34

The bookmark is removed automatically, upon setting text to them. After the next bookmark is assigned, the previous altered text gets removed as well. At the end, I have no bookmarks (from the one I am dealing with) and only the last altered text left. Other bookmarks in the document, not specified by the code are not touched. I have tried to skip the obj_BMRange, but the result was the same. – Vityata 25 май. 16 2016-05-25 09:46:22

So the bookmark is deleted but the text stays there and then upon altering the next bookmark’s text the text that you entered before (that now has no bookmark anymore) gets removed? Do you have different versions of Word installed and can try another one? Also maybe running the macro from Word makes it easier to track down the issue without all the late binding. – arcadeprecinct 25 май. 16 2016-05-25 10:16:21

The first sentence is correct. No other versions on my PC. Probably running it from Word is a good idea, but I really do not want to put my any code there. Anyhow, I have found some kind of workaround — not using bookmarks and just using «replace». Not as fancy, but the result is what I have expected. Thanks! 🙂 – Vityata 25 май. 16 2016-05-25 10:24:46

Instead of ‘obj_BMRange.Text =’, what happens if you use ‘obj_BMRange.InsertAfter «Info2» & vbCrLf’ – LocEngineer 25 май. 16 2016-05-25 10:54:43

2 ответа

The following approach works for me. (Note that I had to remove the lines of code specific to your workbook and files since I don’t have access to any of that. But it doesn’t (shouldn’t) change anything relevant to the problem you present.)

Something that makes no sense in the code you posted is declaring a word_doc variable, then not using it, instead relying on ActiveDocument . I substituted word_doc as appropriate.

I also inserted On Error GoTo 0 to re-instate normal error handling. When you use On Error Resume Next normal error handling is deactivated, which you need for your approach with GetObject . But once the Word application is accessed it needs to be turned back on. Using it at the end of the routine makes no sense.

As mentioned by others, Word removes a bookmark when content is written to it if the bookmark already has content (you see [square brackets]). To get around this, the bookmark needs to be recreated around the content assigned to the Range. Since this involves a couple of steps I wrote a separate function for writing to the bookmark — WriteToBookmarkRetainBookmark .

When I test this from Excel the information is written to each bookmark and the bookmarks exist at the end.

Hi, thanks for the input. I have not tested it yet, but it seems ok. Concerning the on-error handling, in my code I set it back with the following code: If [set_in_production] Then On Error GoTo Main_Error Else On Error GoTo 0 – Vityata 27 май. 16 2016-05-27 07:45:22

Just some workaround I found — using replace in Word — the code is a little «ugly», not dry, but it works:

Still, if someone has an idea about how to solve the original issue, I would like to see it 🙂

Создан 25 май. 16 2016-05-25 10:27:39 Vityata

If you really need to you could implement your own «bookmark» system by using tags and hiding them in the document. Something like §(. )§ and hiding §( and )§. Then use regular expressions to find and replace them. This would let you alter the bookmark content more than once. – arcadeprecinct 25 май. 16 2016-05-25 11:28:22

Can you give an example? I am not quite sure I get what you mean. But is sounds interesting 🙂 – Vityata 25 май. 16 2016-05-25 12:44:09

I imagine something like this: A bookmark looks like ‘§Info001§’ in plain text but you configure it such that ‘§Info001<' and '>§’ are hidden (setting ‘Font.Hidden = true’). I chose ‘§’ in my case because I figured it’s the least likely to appear elsewhere in my document but you can pick anything you like. Then you can write a function that looks for a regular expression that looks like ‘§name<. >§’ and returns the range of ‘. ‘. It’s a lot of effort for something that Word should be able to do better though. – arcadeprecinct 25 май. 16 2016-05-25 13:22:11

Читать еще:  Word object model

Yes, sounds like a good idea, this thing with the regex and the «§» sign. But yeah, it is like an overkill. And my code now looks pretty ok. Thanks! 🙂 – Vityata 25 май. 16 2016-05-25 14:01:46

Bookmarks vba word

Question

I have some code that replaces text at a Word bookmark with a blank so new text can be copied from Excel to Word without removing the bookmark or adding to the text already there. On the line,

Set BMRange = ActiveDocument.Bookmarks(BookmarkToUpdate).Range

I get the ‘error 13 Type mismatch’ error. Here is the code:

The subroutine is run from other code like this:

I am copying data from cells in Excel to bookmarks in word. What do I need to change in the UpdateBookmark subroutine to fix the error. I thought Range is the proper use here. I have the reference libraries in VBA set up for Excel and Word.

Answers

for the variable BMRange, you dim it as a Excel range, which should be a Word.range for a bookmark.You may dim the BMPRange this

And I have made a test to update the bookmark for a word document in an Excel file, it works fine.

Hope this could help you.

We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
Click HERE to participate the survey.

  • Marked as answer by L.Hl Moderator Monday, July 6, 2015 4:24 AM

All replies

Hi,
I have tested the UpdateBookmark sub, it could replace the text for the bookmark in the word.Since we couldn’t reproduce your issue. Could you please share a sample that could appear this problem to fix it if it is convenient.

Best Regards,
Lan

We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
Click HERE to participate the survey.

Here is the complete code:

Hope this helps.

for the variable BMRange, you dim it as a Excel range, which should be a Word.range for a bookmark.You may dim the BMPRange this

And I have made a test to update the bookmark for a word document in an Excel file, it works fine.

Hope this could help you.

We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
Click HERE to participate the survey.

  • Marked as answer by L.Hl Moderator Monday, July 6, 2015 4:24 AM

Hi, I think i’m having a similar problem with a userform. I want a form whereby the user enters details (text) and this text is updated in specific places in the document. I’m currently using bookmarks to achieve this. The only issue I can’t work out how to get that text to multiple locations in the document without coding each bookmark individually and cross referencing doesn’t seem to update.

My current code is:

Private Sub OKbut_Click()
Dim ProductNameasperSPC As Range
Set ProductNameasperSPC = ActiveDocument.Bookmarks(«PNameTitlePage»).Range
ProductNameasperSPC = Me.TextBox1.Value
Dim Active1 As Range
Set Active1 = ActiveDocument.Bookmarks(«Active1TitlePage»).Range
Active1.Text = Me.TextBox2.Value
Dim Active2 As Range
Set Active2 = ActiveDocument.Bookmarks(«Active2TitlePage»).Range
Active2.Text = Me.TextBox3.Value
Dim PLnumber As Range
Set PLnumber = ActiveDocument.Bookmarks(«refnumberTitlePage»).Range
PLnumber.Text = Me.TextBox4.Value
Dim MAHName As Range
Set MAHName = ActiveDocument.Bookmarks(«MAHCAPSTitlePage»).Range
MAHName.Text = Me.TextBox5.Value
Me.Repaint
prodinfo10c.Hide
End Sub

This code works nicely to fill my first page of the document, however, the Pname also features in the header of the next page, and other entries are needed to be repeated also.

Another forum had a solution of:

Sub UpdateBookmark(BookmarkToUpdate As String, TextToUse As String)
Dim BMRange As Range
Set BMRange = ActiveDocument.Bookmarks(BookmarkToUpdate).Range
BMRange.Text = TextToUse
ActiveDocument.Bookmarks.Add BookmarkToUpdate, BMRange
End Sub

But I don’t understand the code, could someone explain, or offer another alternative?

Ссылка на основную публикацию
Adblock
detector