• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 388
  • Last Modified:

Word VBA code fails with 'Object has been deleted' error

I have created a Word macro that works fine when run manually, but when I run it at startup for a template in a Document_New sub it fails:
Private Sub Document_New()
Dim zipCity As String
zipCity = ActiveDocument.Variables("Kunde_adr1")
Dim lenVar As Integer
lenVar = Len(zipCity)
Dim city As String
city = Mid(zipCity, 9, lenVar)
ActiveDocument.Bookmarks("bimCity").Range.Text = city
End Sub

Open in new window

The error is Run-time error '5825': Object has been deleted

Please help me fix this
0
kasperEH
Asked:
kasperEH
  • 5
  • 5
1 Solution
 
DrTribosCommented:
Fails on line 3 or 8?
0
 
kasperEHAuthor Commented:
It fails on line 3, but under Advanced Properties I can see that "Kunde_adr1" is defined.
0
 
DrTribosCommented:
Sure, but might be the case that "ActiveDocument" refers to a document you don't expect OR that the variables are not loaded.

You can add
doEvents

Open in new window

above line 3, or implement some other delay to check.

Also, you can use
debug.print ActiveDocument.Name

Open in new window

to see if you got the document you expect.  The output of debug.print will appear in the Immediate Window Ctrl + G to show / Hide
0
Keep up with what's happening at Experts Exchange!

Sign up to receive Decoded, a new monthly digest with product updates, feature release info, continuing education opportunities, and more.

 
kasperEHAuthor Commented:
I have added the two lines, but I get the same error. ActiveDocument is the current document, the one I am creating. That has been confirmed by the debug.print statement.
0
 
DrTribosCommented:
Well....

debug.print
ActiveDocument.Variables.Count

Open in new window

and if there is more than 0 you could try a small  loop to list them, something like:
For iCount = 1 to ActiveDocument.Variables.Count
debug.print ActiveDocument.Variables(iCount).Name
Next iCount

Open in new window


(Not Tested)
0
 
kasperEHAuthor Commented:
Sorry for the delay. I have tried it now and count of variables is 0. So it probably has something to do with the order things are loaded. Can I execute something after everything is loaded?
0
 
DrTribosCommented:
Google:  Application.Ontime

If needed I'll have time to provide an example later...
0
 
kasperEHAuthor Commented:
Thank you, it works now
0
 
kasperEHAuthor Commented:
Thank you for your help.
0
 
DrTribosCommented:
Good work, glad to help :-)
0

Featured Post

Free Tool: Port Scanner

Check which ports are open to the outside world. Helps make sure that your firewall rules are working as intended.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

  • 5
  • 5
Tackle projects and never again get stuck behind a technical roadblock.
Join Now