简体   繁体   中英

Word VBA Range.Find changes style

I have a document which is autogenerated. Each part of the document has a description and then a list of sentences that are listed as different list items. This works perfectly.

However, there is a need to change the style of certain words that are part of a dictionary, and which may appear anywhere in the text. Given that the dictionary is stored in database, this cannot be hardcoded. The solution is therefore to replace the style of the different words by means of Range.Find.

This solution works perfectly when the words are embedded in a sentence, but changes the bullet style when the word in question is at the beginning of a bulleted sentence.

- DictionaryWord that should be bolded in a list item

becomes

DictionaryWord that should be bolded in a list item

However,

- This DictionayWord is however bolded correctly without removing the "list" style

I have tried to enter a dummy text before the first word, and then delete it by means of anothe Range.Find, but the issue remains the moment I delete the dummy text.

The code for changing the dictionary words is as follows:

 Set oRange = oDoc.Content
 With oRange.Find
    .Replacement.ClearFormatting
    .Format = True
    .Forward = True
    .MatchCase = True
    .MatchWholeWord = True
    .Wrap = wdFindContinue
    Set rsdictionary = DB.OpenRecordset("qrydictionaryterms", dbOpenSnapshot)
    .Replacement.Style = "Dictionary Style"
    While Not rsdictionary .EOF
        .Execute findtext:=rsdictionary ("CDMStereotype"), MatchCase:=True, Replace:=wdReplaceAll
        rsdictionary .MoveNext
     Wend
 end with

I would greatly appreciate any suggestions about how to fix this.

Thanks to everybody who provided an answer, but it looks as if nothing was wrong with my code.

For others who may encounter this problem in the future, please find the explanation below:

The issue is that the applied style for DictionaryWord is based not on the default paragraph style, but rather on another style. It seems that Word applies the style stepwise, and the first thing it does is to apply the style on which the DictionaryWord style is based (which removes the bullets), then apply the DictionaryWord style.

The solution to this is to define the DictionaryWord as a Character style based on the default paragraph style, so that no other styles are applied first.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM