Bizarre VBA error

  • Thread starter Roderick O'Regan
  • Start date
R

Roderick O'Regan

I'm getting a VBA error which I cannot fathom out why it's happening.

Here's what I'm doing:
I create a document and run the following code to create a large white
box in a deep top margin of 10cm (that's what client wants!)

ActiveDocument.Shapes.AddShape(msoShapeRectangle, 10, 50, 10,
10).Select
With Selection.ShapeRange
.RelativeHorizontalPosition = _
wdRelativeHorizontalPositionPage
.RelativeVerticalPosition = _
wdRelativeVerticalPositionPage
.Left = CentimetersToPoints(3)
.Top = CentimetersToPoints(1.98)
.Width = CentimetersToPoints(17.5)
.Height = CentimetersToPoints(7.4)
.Fill.ForeColor.RGB = RGB(255, 255, 255)
.Line.Visible = msoFalse
.LockAnchor = True
.WrapFormat.AllowOverlap = True
.WrapFormat.Type = 3
.ZOrder msoSendBehindText
End With
Selection.Collapse

Within this white box goes a single cell table in which the user has
to type a title.

I then add another section and repeat the code above but the following
error appears:
"The RelativeHorizontaPosition method or property is not available
because the drawing operation cannot be applied to the current
selection" (It's error 4605)

Here's the weird bit:
If I don't type a title in the table contained in the first section I
can add the box OK in the second.

If I do add that title then try and run the code again in the second
section I get the error.

Can anyone suggest why I'm getting this error, please? And then only
in certain circumstances?

Roderick
 
J

Jezebel

At a guess, Word is barfing at the attempt to add a shape within a cell
within a shape. If you don't add the title, the selection remains in the
body of the document, so there's no problem; if you add a title, the
selection is then within the cell where you add it.

You would likely avoid the problem if you made no reference to the selection
object: use Range objects exclusively, eg --

Dim pShape as Word.Shape
Dim pTable as Word.Table
Set pShape = ActiveDocument.Shapes.AddShape(msoShapeRectangle, 10, 50, 10,
10)
With pShape
.RelativeHorizontalPosition = ...
:
End with
set pTable = pShape.TextFrame.TextRange.Tables.Add(...)
pTable.Cell(1,1).Range = "Text inserted in table cell"


But even better, predefine the shape as an autotext entry; then simply
insert it. This is not only simpler to code, but means you can modify the
size, shape, and position of the shape simply by redefining the AutoText
entry, without having to modify your VBA code.
 
R

Roderick O'Regan

Thanks Jezebel for your ideas. I ended up using the Range objects as
suggested below and that did the trick.

Thanks again for your help

Roderick
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top