2
votes

I am writing a macro in Excel that opens and manipulates a Word document. The code works when I run it through the vba editor in word but when I import the lines of code into my excel macro I get a run-time 438 error.

Word Macro

Selection.Collapse WdCollapseDirection.wdCollapseEnd

Code inserted into Excel macro, with wtemp being the word document object

wtemp.Activate
wtemp.Tables(3).Select
wtemp.Activate
wtemp.Selection.Collapse WdCollapseDirection.wdCollapseEnd

I believe the issue lies with the selection object, or that I am missing a reference. The references that I have included in VBAProject are:

  • Visual Basic for Application
  • Microsoft Excel 16.0 Objects Library
  • OLE Automation
  • Microsoft Office 16.0 Office Library
  • Microsoft Word 16.0 Office Library
  • Microsoft Forms 2.0 Object Library
  • Microsoft Scripting Runtime
1

1 Answers

5
votes

The document object doesn't have a Selection property, but the Word Application does.

If you have a reference to the Word Application, you can use code like this:

Dim wd As Word.Application
Set wd = GetObject(, "Word.Application")

Dim wtemp As Word.Document
Set wtemp = wd.ActiveDocument

wtemp.Activate
wtemp.Tables(3).Select
wtemp.Activate
wd.Selection.Collapse WdCollapseDirection.wdCollapseEnd