Home > database >  move selection to end of word document
move selection to end of word document

Time:10-05

i have a word document that has text in it, when the document opens the selection is in the very first line of the document so when I run the code below to add a new page the whole text moves to the new page, how do I move the selection to the end of the document so that when I add a new page the text does not move to the new page?

edit: tried below but does not work

"objSelection.EndKey Unit:=wdStory, Extend:=wdMove"

"objWord.Documents("letters.docx").Selected.EndKey Unit:=wdStory, Extend:=wdMove"

Sub exceltoword()

Dim objWord As Object

Set objWord = CreateObject("Word.Application")
objWord.Visible = True
objWord.Documents.Open "C:\Users\WORK\Desktop\letters.docx"
objWord.Activate
Set objSelection = objWord.Selection

'**MOVE TO END OF DOCUMENT BEFORE ADDING NEW PAGE**
'tried objSelection.EndKey Unit:=wdStory, Extend:=wdMove --- does not work
'tried objWord.Documents("letters.docx").Selected.EndKey Unit:=wdStory, Extend:=wdMove --- does not work
objSelection.InsertNewPage

objWord.Application.Quit
Set objWord = Nothing

End Sub

CodePudding user response:

Your issue is a result of your use of late binding, declaring objWord As Object instead of setting a reference to the Word object library.

enter image description here

When using late binding you cannot use the enums or constants from the Word object library as Excel doesn't know what those represent. You either have to declare those constants yourself or use their underlying values.

Actually there is little value to using late binding in this instance. The only advantage to late binding is version independence, i.e. you can write code in a newer version and it will theoretically work in an older one. But that advantage is lost unless you also use late binding for the host application code as Office is usually installed as a package. It is better to use early binding when working with other Office applications and reserve late binding for other commonly used libraries, e.g. ADO or XML.

If you want to know more about late binding see https://rubberduckvba.wordpress.com/2019/04/28/late-binding/

I also noticed that you are not using Option Explicit at the top of the code module, as your code contains undeclared variables. To add this automatically to new modules open the VBE and go to Tools | Options. In the Options dialog ensure that Require Variable Declaration is checked.

You should also break the habit of using Selection. There is rarely any need to select anything when using VBA.

So your code should look similar to this:

Sub exceltoword()
    Dim wdApp As Word.Application
    Set wdApp = CreateObject("Word.Application")
    wdApp.Visible = True
    Dim wdDoc As Word.Document
    Set wdDoc = wdApp.Documents.Open("C:\Users\WORK\Desktop\letters.docx")
    wdDoc.Characters.Last.InsertBreak Type:=wdPageBreak
    wdApp.Quit
    Set wdApp = Nothing
End Sub
  • Related