Word VBA Macro crashes only when Word is not visible

N

Nick Biggs

I am using Microsoft Word 2002 (10.4219.6735) SP3 and I have a problem with
running a VBA macro while Word is set with Visibility set to False. It runs
fine when Word is visible.

My production code is actually in VB6 which is driving Word through
automation. It is trying to turn the borders off for some cells in a table
and it is messing up big time. This is part of a report generation solution
and needs to run with Word non visible.

I have taken my VB6 code and reduced the problem down to the following Word
VBA code which exhibits a more catastrophic problem. The problem seems to be
with using the "Selection" while Word is not visible.

Can anyone let me know how I can update the border line style in a table
with Word not visible.

Sub TableProblem()
Dim aTable As Word.Table
Dim i As Integer

Application.ScreenUpdating = False
Application.Visible = True
' Application.Visible = False ' Uncomment this a see the problem

'Start by clearing everything from the current document
Selection.WholeStory
Selection.Delete

Set aTable = Tables.Add(Selection.Range, 121, 5)
aTable.AutoFormat wdTableFormatGrid1, True

For i = 1 To 30
Selection.MoveDown Unit:=wdLine, Count:=1
Selection.MoveRight Unit:=wdCharacter, Count:=1
Selection.MoveDown Unit:=wdLine, Count:=2, Extend:=wdExtend
Selection.MoveRight Unit:=wdCharacter, Count:=2, Extend:=wdExtend
Selection.Borders(wdBorderHorizontal).LineStyle = wdLineStyleNone
Selection.Shading.BackgroundPatternColor = wdColorGray05
Selection.MoveLeft Unit:=wdCharacter, Count:=2
Selection.MoveDown Unit:=wdLine, Count:=3
Debug.Print i
Next i

Application.Visible = True
Application.ScreenUpdating = True
End Sub
 
H

Howard Kaikow

Ayup, do not use the Selection object when Word is not visible, instead use
the Range object.

It's a good idea to use the Range object instead of the Selection object in
nearly all cases anyway.
 

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