End of document vba word

word-vba-tutorial-susan
Image: Sai/Adobe Stock

Visual Basic for Applications is the language behind the Office apps that allows you to automate tasks. But using VBA in Word has its challenges. The first is moving around in a document because of all the different types of content: Text, pictures, tables and so on. In this tutorial, I’ll show you two simple VBA procedures for navigating. One identifies the beginning of a Word document, and the other identifies the document’s end.

I’m using Microsoft 365 on a Windows 10 64-bit system, but you can use an earlier version. You may access the demo files here. Word for the web doesn’t support VBA.

SEE: Google Workspace vs. Microsoft 365: A side-by-side analysis w/checklist (TechRepublic Premium)

About Microsoft Word VBA’s ActiveDocument

The main VBA component that we’ll rely on in both procedures is the ActiveDocument property, which returns a Document object that represents the active document. In other words, this opens the document, as a whole. You won’t need this for every VBA procedure in Word, but you will need it when you need to reference “parts” of the document.

If no Word document is open, this property returns an error. If you’re using this property from inside Excel or PowerPoint, you should include error-handling for this situation.

This property uses the following form:

expression.ActiveDocument

where expression is a variable that represents the Application object (Word). Fortunately, in Word, this is implicitly implied.

The next piece of VBA we’ll use is the Range method, which uses the form

expression.Range(start, end)

to return a Range object. We’ll use this method to identify an area of the document.

There’s no method that says “go to the beginning,” or “go to the end,” so we’ll use the start and end arguments to identify both. Both arguments are optional, and as you might suspect, start identifies the first character position and end identifies the last character position.

Now, let’s move on to the actual VBA procedures.

How to use VBA to find the beginning of a Word document

Moving the cursor to the beginning of a Word document using VBA is amazingly simple. Listing A shows the procedure. First, the procedure declares and defines a range object, using 0s to identify the beginning of the document. Two 0s will place the cursor before any content in the active document. The second line adds a bit of text and the vbNewLine constant adds a new line.

Listing A

Sub GoToStart()

'Move cursor to the beginning of the active document.

'Add a short text phrase to show it worked.

Dim rBegin As Range

Set rBegin = ActiveDocument.Range(0, 0)

rBegin.Text = "This is the beginning of this document." & vbNewLine

End Sub

Now let’s look at the second procedure that moves the cursor to the end of a document.

How to use VBA to find the end of a Word document

As mentioned, there is no method that says “go to the end,” so we need to force the issue by finding the last character. It is a bit more complex, but not difficult, as shown in Listing B. This procedure works similar to the first, but it enters the text at the end of the document, which it finds by using the Last property of the Characters object.

This time we positioned the vbNewLine constant before the text.

Listing B

Sub GoToEnd()

'Move cursor to the end of the active document.

'Add a short text phrase to show it worked.

Dim rEnd As Range

Set rEnd = ActiveDocument.Range.Characters.Last

rEnd.Text = vbNewLine & "This is the end of this document."

End Sub

How to enter and run the VBA procedures into a Word document

Now it’s time to enter both procedures for use in a Word document. I’m using a short two-page Word document, shown in Figure A, with a variety of content saved as a macro-enabled Word file. If you are using a ribbon version, you must save the Word document as a macro-enabled file to run VBA. If you’re working in the menu version, you can skip this step.

Figure A

WordVBA_A

Image: Susan Harkins/TechRepublic. The VBA procedures will add a bit of content to the beginning and the end of this Word document.

To enter the VBA procedures, press Alt + F11 to open the Visual Basic Editor (VBE). In the Project Explorer to the left, select ThisDocument. You can enter the code manually or import the downloadable .cls file. In addition, the procedure is in the downloadable .docm and .doc files. If you enter the code manually, don’t paste from this web page. Instead, copy the code into a text editor and then paste that code into the ThisDocument module. Doing so will remove any phantom web characters that might otherwise cause errors.

Now let’s run the procedures as follows:

  1. Click the Developer tab.
  2. Choose Macros in the Code group.
  3. In the resulting dialog, choose GoToStart (Figure B).
  4. Click Run.

As you can see in Figure C, the procedure inserts text and a line break at the beginning of the Word document. Now let’s repeat this process but choose GoToEnd (Figure B). This procedure inserts a line break and a bit of text to the end of the Word document, as you can see in Figure D.

Figure B

WordVBA_B

Image: Susan Harkins/TechRepublic. Choose the procedure.

Figure C

WordVBA_C

Image: Susan Harkins/TechRepublic. GoToStart() added a sentence to the beginning of the Word document.

Figure D

WordVBA_D

Image: Susan Harkins/TechRepublic. GoToEnd() added a sentence to the end of the Word document.

One thing you might notice is that both of the inserted sentences use different formats. These sentences, like any other, will use the format in place. This is worth remembering if you want inserted text to use a specific format instead.

Most likely, you won’t want to work through all those steps to run this macro. I recommend that you add it to the Quick Access Toolbar or a custom group. If you need help with that, read How to add Office macros to the QAT toolbar for quick access.

Stay tuned

Both VBA procedures are simple — both the procedures themselves and the tasks they complete. The goal is to show you how to navigate to both spots using VBA. Over the next few months, I’ll devote a few articles to more navigational VBA in Microsoft Word documents.

Identify End of Document using Word VBA

Find End Of Document using Word VBA

Most often when we loop through the document, we need to know the End of Word Document. We can achieve that by using Bookmarks

Sub Drive_IS_EOD()

If IS_EOD(Selection.Range) = True Then
MsgBox «End of Document»
Else
MsgBox «Miles to Go:)»
End If

End Sub

The function below uses the Exists method to check if the bookmark exist in the specified range

Function IS_EOD(ByRef MRange As Range) As Boolean

If MRange.Bookmarks.Exists(«EndOfDoc») = True Then
IS_EOD = True
End If

End Function

EndOfDoc is a predefined bookmark, which is used here

StumbleUpon

Related Posts Plugin for WordPress, Blogger...

In my vba code I need to go to the end of the word document.
The vba is written and executed from Excel.
The statement : Selection.EndKey unit:=wdStory, Extend:=wdMove » will not run.
Can anyone explain where I do the mistyping.

I have tried to use the statement in other vba codes, but without success.

Sub InsertFromFilesTestEnd()


Dim wrdApp As Word.Application
Dim wrdDoc As Word.Document


    Set wrdApp = New Word.Application
    Set wrdDoc = wrdApp.Documents.Open("c:userspeterdocumentsdirekte 0302 1650.docm")
        wrdApp.Visible = True
        wrdApp.Activate
        Application.ScreenUpdating = False

Selection.EndKey unit:=wdStory, Extend:=wdMove
End Sub

Hopefully you can guide me to the end of my document. When so, I am sure I can use «selection» to move around in the document.

Cindy Meister's user avatar

asked Feb 8, 2019 at 13:04

Peter Grandjean's user avatar

2

The issue here is that Selection isn’t qualified to which application’s Selection you are wanting. As such, it’s using the default for Excel VBA, which would be the Excel Application in which the VBA was launched. Implicitly you are saying:

Application.Selection.EndKey unit:=wdStory, Extend:=wdMove

The error is because Excel’s Application.Selection object doesn’t have an EndKey method and so VBA has no idea what you are trying to do here.

Instead you want to qualify that Selection with the instance of the Word.Application object you are already working with:

wrdApp.Selection.EndKey unit:=wdStory, Extend:=wdMove

answered Feb 8, 2019 at 13:57

JNevill's user avatar

JNevillJNevill

45.8k3 gold badges36 silver badges60 bronze badges

0

Using Selections in cases like this is quite unnecessary. Aside from being inefficient, it’s also prone to producing a lot of screen flicker. Try, for example:

Sub InsertFromFilesTestEnd()
Dim wrdApp As Word.Application
Dim wrdDoc As Word.Document
Set wrdApp = New Word.Application
With wrdApp
    .Visible = True
    .ScreenUpdating = False
    Set wrdDoc = .Documents.Open("c:userspeterdocumentsdirekte 0302 1650.docm")
    With wdrDoc
        .Range.Characters.Last.InsertFile FileName:="MyFileName", Range:="", _
            ConfirmConversions:=False, Link:=False, Attachment:=False
    End With
    .Activate
    .ScreenUpdating = True
End With
End Sub

answered Feb 10, 2019 at 20:30

macropod's user avatar

macropodmacropod

12.6k2 gold badges9 silver badges21 bronze badges

  • Remove From My Forums
  • Question

  • I’ve been trying desperately to do something which ought to be simple. Can anyone tell my the code in Word 2007 to:

    Do until you get to the end of the document.

    It’s the «end of the document» part that I’m having so much trouble finding.

    Any and all help is appreciated.

    Peg

Answers

  • It depends on the way you loop. For example, if you are ‘finding’ some text, you can use

    Do until Selection.Find.Found = False

    Or if you are going by PAragraphs

    For i = 1 To ActiveDocument.Paragraphs.Count
        MsgBox ActiveDocument.Paragraphs(i).Range.Text
    Next i
    

    You can use the same way for Lists, Ranges, Sections etc

    If you are in some portion of the document and want to know, if the EOD is reached you can use the following:

    If Selection.Bookmarks.Exists("EndOfDoc") = True Then
       MsgBox "I have reached EOD"
    End If
    

    Cheers
    Shasur


    http://www.vbadud.blogspot.com

    • Marked as answer by

      Wednesday, August 5, 2009 3:12 AM

Word VBA, End of File

Jun 14, 2015 in VBA for Word

In this article I will explain how you can check if you’ve reached the end of a word document using VBA. In the articles below I’ve explained how to get the current page and line number the cursor is on:

  • Word VBA, Get Current Line Number
  • Word VBA, Get Current Page Number

Using the code below you can get the last line and page number of the document:

Sub main()
Dim intLastLine As Integer
Dim intLastPage As Integer

'go to the last line
Selection.EndKey unit:=wdStory
'get last line
intLastLine = _
    Selection.Range.Information(wdFirstCharacterLineNumber)
'get last page
intLastPage = _
    Selection.Range.Information(wdActiveEndPageNumber)
End Sub

By comparing the current position of the cursor with last line and last page we can determine whether we have reached the last line or not.

Note: The line numbers obtained are relative to the page. That means that the line number starts from “1” at the start of each page. That is why we need to have both the page number and the line number to determine if we have reached the end of the document or not.

A complete example of using this method has been used in the article below:

  • Word VBA, Read All Lines

See also:

  • Word VBA, Get Current Page Number
  • Word VBA, Get Current Line Number
  • Word VBA, Move Cursor to End of Document

If you need assistance with your code, or you are looking for a VBA programmer to hire feel free to contact me. Also please visit my website  www.software-solutions-online.com

Понравилась статья? Поделить с друзьями:
  • Encyclopedia meaning of the word
  • Encouraging word of the day
  • Encouraging word for friends
  • Encourage word for the day
  • Encourage word for teacher