'VBA macro error, Requested object is not available
Admittedly I'm not very familiar with VBA, and I've only ever used it for this one small macro that I've used once before. Essentially, I'm trying to take a MailMerge document, and save each individual document with the same naming format based on the values in the MailMerge. I did a ton of tinkering with this about 4 years ago and got it to work, but for some reason now I'm unable to get it to function without throwing the following error:
"Run-time error '5852' : Requested object is not available."
I'm not sure what's causing the issue, and can't recall what I did last time that made it work without issues, so I was hoping someone here might have some insight. Honestly there's a good chance some of this code was copied and pasted from here as well, but here is the code I have as of now:
Sub SaveDocumentsSeparetely()
'Used to set criteria for moving through the document by section.
Application.Browser.Target = wdBrowseSection
DocNum = 100
'A mailmerge document ends with a section break next page.
'Subtracting one from the section count stop error message.
For i = 1 To ((ActiveDocument.Sections.Count) - 1)
'Select and copy the section text to the clipboard
ActiveDocument.Bookmarks("\Section").Range.Copy
'Create a new document to paste text from clipboard.
Documents.Add
Selection.Paste
'Removes the break that is copied at the end of the section, if any.
Selection.MoveUp Unit:=wdLine, Count:=1, Extend:=wdExtend
Selection.Delete Unit:=wdCharacter, Count:=1
ChangeFileOpenDirectory <PATH>
DocNum = ActiveDocument.MailMerge.DataSource.DataFields(1).Value
LastName = ActiveDocument.MailMerge.DataSource.DataFields(4).Value
ActiveDocument.SaveAs FileName:="BaseFileName_" & LastName & "_" & DocNum & ".doc"
ActiveDocument.Close
'Move the selection to the next section in the document
Application.Browser.Next
Next i
ActiveDocument.Close savechanges:=wdDoNotSaveChanges
End Sub
The line throwing the error is this one:
DocNum = ActiveDocument.MailMerge.DataSource.DataFields(1).Value
I'm aware that the error refers to not being able to access the data field at the time I'm running the script, but I'm not sure why that would be, since I'm running it from the MailMerge document.
If anyone can help with this I would really appreciate it.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
