Dave Reilly
Dave Reilly

Reputation: 65

Write and Style In Loop

Say that I have the following code to write headings from an array to a word document and to apply defined styles:

With wdDoc
    Set wrdRange = .Range(0, 0)                     ' Set initial Range.
    i = 2
    Do Until i > 6
       ' Debug.Print wrdRange.Start, wrdRange.End
        wrdRange.text = totalArray(i, colIndex(3)) & Chr(11)
        Set wrdRange = .Paragraphs(i - 1).Range
        wrdRange.Style = totalArray(i, colIndex(2))
        wrdRange.Collapse 0
        i = i + 1
    Loop
End With

One would expect the following to occur:

  1. The word range moves programmatically as I move through the document.
  2. The word style is updated for the new range (defined by the set statement)
  3. The Range collapses to the end (0 = wdCollapseEnd) and the loop continues until the initial conditions are satisfied.

What I can't seem to fix is the styles being applied to ALL existing paragraphs in the document. The Debug.Print statement should show the range being updated as expected, despite the fact that the style applies to all existing paragraphs.

As you can tell, I've toyed around with this quite a bit, to no avail. Any help would be appreciated in this matter.

Thanks.

Upvotes: 0

Views: 73

Answers (1)

Cindy Meister
Cindy Meister

Reputation: 25673

In the following line of code:

 wrdRange.text = totalArray(i, colIndex(3)) & Chr(11)

Use Chr(13) instead of Chr(11). The latter is simply a line break, not a new paragraph. So applying a style to any part of the Range is actually applying it to all the text your code is generating because it's a single paragraph.

Upvotes: 1

Related Questions