PDA

View Full Version : [SOLVED:] Macro wont run except...



austenr
07-07-2005, 11:40 AM
This is a strange problem. I am trying to run the code below from the menu on the worksheet. If I do it that way it errors out on the .Documents.Add line. However, if you stay in the VBE and step through it using F8 it works.


Option Explicit

Sub CopyTableToAnyWordDocument()
Dim wdApp As Word.Application
ThisWorkbook.Sheets("Table").Range("A1:B6").Copy
On Error Resume Next
Set wdApp = GetObject(, "Word.Application")
If wdApp Is Nothing Then
Set wdApp = GetObject(" ", "Word.Application")
End If
On Error GoTo 0
With wdApp
.Documents.Add
.Visible = True
End With
With wdApp.Selection
.EndKey Unit:=wdStory
.TypeParagraph
.Paste
End With
Set wdApp = Nothing
End Sub


I have attached the workbook also. :dunno

Jacob Hilderbrand
07-07-2005, 12:00 PM
Looks like you are confusing Early and Late binding here. This should work for you.



Option Explicit

Sub CopyTableToAnyWordDocument()
Dim wdApp As Word.Application
ThisWorkbook.Sheets("Table").Range("A1:B6").Copy
Set wdApp = New Word.Application
With wdApp
.Documents.Add
.Visible = True
End With
With wdApp.Selection
.EndKey Unit:=wdStory
.TypeParagraph
.Paste
End With
Set wdApp = Nothing
End Sub

mdmackillop
07-07-2005, 12:00 PM
Try



If wdApp Is Nothing Then
Set wdApp = CreateObject("Word.Application")
End If

austenr
07-07-2005, 12:08 PM
Both work..Thanks DRJ, MD Solved. Although I never could really grasp the Early and Late Binding concept. Can anyone briefly expalin. Thanks

Justinlabenne
07-07-2005, 12:27 PM
How about here (http://word.mvps.org/FAQs/InterDev/EarlyvsLateBinding.htm) & here (http://www.dicks-clicks.com/excel/olBinding.htm)

Bob Phillips
07-07-2005, 02:35 PM
Both work..Thanks DRJ, MD Solved. Although I never could really grasp the Early and Late Binding concept. Can anyone briefly expalin. Thanks

It is not necessarily anything to do with early/late-binding. CreateObject and GetObject work equally well with both. Binding referes to when the type library is bound to the application, early - before compilation, or late - at run time.