PDA

View Full Version : Why do macros work once and then stop? Example is included



AshZM
10-27-2022, 03:21 PM
Hi,

(not sure if I should post to Mac group - not cross-posting)

Sometimes I will copy someone's macro and when I run it the first time, it works. Next time, it does not.
It has happened after an object has been set. One error type I get is Run-time 438 "Object doesn't support this property or method."

The below code worked the first time. The second time, it had an automation error Run-time error '-2146959355 (80080005)'. I cannot figure out a pattern for when it does not work. It's sometimes okay after word is closed. It sometimes works if word is open with one document... I'm not really concerned with the below vba getting fixed (doesn't meet my actual needs). I just want to know why these errors keep happening on subsequent Runs.


Sub main()
Dim objWord As Object
Dim objDoc As Object
Set objWord = CreateObject("Word.Application")
objWord.Visible = True
Set objDoc = objWord.Documents.Add
Dim i As Integer
Dim strValue As String
'below only pastes B6, not sure why. Don't care
For i = 1 To 5
'bring focus to the document created
objDoc.Activate
'read the value from the cell
strValue = Cells(i + 1, 1)
'write the value to the document
objWord.Selection.TypeText Text:=strValue
'move to the next line
objWord.Selection.TypeParagraph
Next i
End Sub


What I eventually want, which is probably another post, is to have Excel paste a chart into the active word document. I don't want it opening a new document. I'd like to paste where the cursor is. Everything I'm finding has Word open a new document first, which doesn't save me any work.

Thanks!
-Ashley

SamT
10-27-2022, 06:40 PM
Delete the "objDoc.Activate line"
If that isn't enough, move it before the loop.

AshZM
10-27-2022, 07:46 PM
Still getting an error. Although it still creates a new document.
Is there a way to get something from Excel to paste into the currently active word document?

errors, leave ;-). "their" would have been incorrect back in the day.

Thanks,
-Ashley

snb
10-28-2022, 12:34 AM
If you want to write something from Excel into an already open Worddocument, named "G:\OF\example.docx"


Sub M_snb()
With getobject("G:\OF\example.docx")
.Paragraphs(1).range.text="snb"
end with
End Sub

NB. VBA has been invented to make your programming life easier.