0
votes

I'm trying to achieve something very simple. To select the items of a bullet list, run a macro and have those items shuffled randomly. I never used VBA in MS-Word so I started with very small steps, but even those seem to be hard to follow. My strategy is to insert items one at a time. The text of each newly-added paragraph would be the text of a randomly selected item from the selection. When the number of added paragraphs equals the number of items selected, I start to remove the original items in the selection.

This is my initial draft. It doesn't perfectly replicate my strategy but I need answers about the basics to continue.

Sub test()
Dim pars As Paragraphs
Dim rng As Range

' The selection is items from a bullet list (4 items).
Set pars = Selection.Paragraphs

' I have to do that if I don't want to overwrite the last element, though it is never filled later.. why?
pars.Add

' Simulate some shuffling here..
pars.Add.Range.FormattedText = pars(2).Range.FormattedText
pars.Add.Range.FormattedText = pars(1).Range.FormattedText
pars.Add.Range.FormattedText = pars(3).Range.FormattedText
pars.Add.Range.FormattedText = pars(4).Range.FormattedText

' The total number of paragraphs should be 8..
MsgBox pars.Count

' Now remove the top 4 paragraphs to keep just the last ones I added..
For i = 1 To 4
    pars(1).Range.Delete
Next i

' I should get a message with 4 in it, instead I'm getting 1.. why??
MsgBox pars.Count

End Sub

My question is: what is the flow of adding paragraphs? How can I remove paragraphs?

1
Here are two sites with some info on deleting paragraphs: one, twoMarcucciboy2

1 Answers

1
votes

Your instinct about using a Range object is good, even though your code doesn't actually use it. Instead of using Selection.Paragraphs set Selection.Range to the Range - the Range will contain the Paragraphs. This is the original, that you'll later delete.

Declare a second Range as the target for the new paragraphs, using the Range.Duplicate property to make a "copy" of the original Range. "Collapse" this to its end-point. This way, when you add the paragraphs they'll "tack on" to the end of the original Range.

Good use of Range.FormattedText for "copying" the paragraphs. Again, collapse the target Range after each addition to avoid replacing what you added in the previous iteration of the loop.

At the end, delete the original Range.

Sub ShuffleBullets1()
    Dim pars As word.Paragraphs
    Dim rngNewPars As word.Range
    Dim rngOldPars As word.Range
    Dim i As Long

    Set rngOldPars = Selection.Range
    Set rngNewPars = rngOldPars.Duplicate
    rngNewPars.Collapse wdCollapseEnd
    Set pars = rngOldPars.Paragraphs
    For i = pars.Count To 1 Step -1
        rngNewPars.FormattedText = pars(i).Range.FormattedText
        rngNewPars.Collapse wdCollapseEnd
    Next
    rngOldPars.Delete
End Sub