Elliot Tan
Elliot Tan

Reputation: 149

Insert Building Blocks using Word VBA

I'm trying to insert a formatted table that I have saved in word named "DV Table" as part of the building blocks using VBA. I need this table to be inserted at the 13th paragraph of the word document. Here's my code below. The first 3 lines just sets the selection to be at the 12th paragraph and create a new paragraph (13) after that. The last line of code is to insert the table. But when I run this, it gives the error.

Compile Error: Sub or Function not defined

I guess that this is not the proper way of defining the location. Would like some help on this. Thanks.

ActiveDocument.Paragraphs(12).Range.Select
Selection.EndKey Unit:=wdLine
Selection.Paragraphs.Add

 ActiveDocument.AttachedTemplate.BuildingBlockEntries("DV Table" _
      ).Insert Where:=Paragraphs(13).Range.Select, RichText:=True

Upvotes: 1

Views: 1839

Answers (1)

Cindy Meister
Cindy Meister

Reputation: 25663

The Where parameter requires a Range object. There are two problems with Paragraphs(13).Range.Select

  • it's a method - it's an action, selecting something, not returning an object
  • Paragraphs(13) isn't "fully qualified" - VBA doesn't know what it is/what is meant.

One possibility would be

ActiveDocument.Paragraphs(13).Range

Notice ActiveDocument. preceding Paragraphs: this "fully qualifies" Paragraphs(13) - it tells VBA to what that belongs. And, since Where requires a Range object, Paragraphs(13).Range should be a correct "target" (I have not tested your code).

Generally, it's preferable not to work with Selection, just with Range objects. There's usually no need to actually select something using VBA. An alternative to the code snippet in the question could be

Dim rng As Word.Range

Set rng = ActiveDocument.Paragraphs(13).Range
rng.Collapse wdCollapseEnd    'like pressing right-arrow for a selection
rng.InsertParagraphAfter
rng.Collapse wdCollapseStart  ' like pressing left-arrow for a selection
'rng.Select                   ' for testing / demo purposes
ActiveDocument.AttachedTemplate.BuildingBlockEntries("DV Table" _
               ).Insert Where:=rng, RichText:=True

In this case, the selection in the document does not change. There's no screen flicker; and code executes more quickly. This way of working takes getting used to, but once one is familiar with it, it's much easier to recognize what the code should be doing... Selection is rather vague as to what is being manipulated, especially if there's a lot of code using it.

Upvotes: 2

Related Questions