I'm trying to write a macro that adds subdocuments to the end of a Word document when the Word document is opened. The document in question already has some text in it, so before running the macro I'd like to move the cursor to the end of the document. I can achieve this with the code: Selection.EndKey Unit:=wdStory
which works fine when I run the macro after opening the document, but if I run the macro as soon as the document is opened by using the Sub:
Private Sub Document_Open()
Selection.EndKey Unit:=wdStory
'Add subdocuments based on user input to a form
'(See edit below)
End Sub
in the ThisDocument object, the subdocuments are added at the start of the document. This may be because the cursor has not yet appeared so Selection
doesn't 'exist' yet.
How do I run my macro when the document opens, but add subdocuments to the end of the document?
I've tried writing a space out first to cause the cursor to spawn but no change...
Any suggestions for alternative methods also welcome.
Edit: This code in ThisDocument:
Private Sub Document_Open()
CreateWorkbook.Show
End Sub
Calls the form CreateWorkbook, with a button click sub:
Private Sub GenerateButton_Click()
Dim i As Integer
Dim rng As Word.Range
Set rng = ActiveDocument.Content
rng.Collapse wdCollapseEnd
'ModulesListBox is a user input box that is a list of paths to the subdocuments
For i = 0 To ModulesListBox.ListCount - 1
docpath = ModulesListBox.List(i)
rng.Subdocuments.AddFromFile docpath
Next i
End Sub
Selection.Wholestory
before that line. – dwirony