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.

We are manipulating our Word 2007 documents from .Net using Word Interop. Mostly doing stuff with fields as in:

For Each f In d.Fields
    f.Select()
    //do stuff with fields here            
Next

This leaves the last field in the document selected.

So, for the sake of neatness we would like to position the cursor at the end of the document (or even the start would be OK).

Googling for the answer doesn’t throw up much … the nearest I can get seems to be suggesting we need to involve ourselves with ranges or bookmarks. There’s a GoTo method for the Document object but none of the WdGoToItem options it offers are useful.

Isn’t there a simple way to just send the cursor to the end (or start) of document?

Edit

Part of my problem was I didn’t like leaving the last field selected. Have now realised that I can do

f.Unlink

to remove the mergefield and just leave the field text there as plain text. Which is neater, whether or not we also reposition the cursor

ivcubr's user avatar

ivcubr

1,8789 gold badges19 silver badges27 bronze badges

asked Oct 19, 2009 at 23:20

hawbsl's user avatar

@Alexander Kojevnikov: Thanks for your help because you put me on the right track. However I found I had to apply the .GoTo to the Word Selection object, not the Document. As in:

    Dim what As Object = Word.WdGoToItem.wdGoToLine
    Dim which As Object = Word.WdGoToDirection.wdGoToLast

    //below line had no effect
    //d.GoTo(what, which, Nothing, Nothing)

    w.Selection.GoTo(what, which, Nothing, Nothing)

answered Oct 20, 2009 at 8:45

hawbsl's user avatar

hawbslhawbsl

15.1k24 gold badges73 silver badges113 bronze badges

4

This is how it looks in C#:

object missing = Missing.Value;
object what = Word.WdGoToItem.wdGoToLine;
object which = Word.WdGoToDirection.wdGoToLast;
doc.GoTo(ref what, ref which, ref missing, ref missing);

I guess it will be even easier in VB.Net as it supports optional parameters.

answered Oct 19, 2009 at 23:49

Alexander Kojevnikov's user avatar

0

I’m not sure I’m using the same environment as you, but to go to the start or end of the document here’s what works for me:

Private Sub moveCursorToStartOfDocument()
    w.Selection.HomeKey(WdUnits.wdStory, Nothing)
End Sub

Private Sub moveCursorToEndOfDocument()
    w.Selection.EndKey(WdUnits.wdStory, Nothing)
End Sub

answered Feb 21, 2014 at 3:44

Fuhrmanator's user avatar

FuhrmanatorFuhrmanator

11k6 gold badges60 silver badges106 bronze badges

I use unit Word_TLB in Delphi with Appliction object- Word.Application

as following:

aWordDoc.Application.Selection.EndKey(wdStory,wdMove);

generally end of word document is:

Selection.EndKey( WdUnits.wdStory, WdMovementType.wdMove)

When I use

Selection.GoTo(Word.WdGoToItem.wdGoToLine, Word.WdGoToDirection.wdGoToLast, Nothing, Nothing);
Selection.InsertFile('documnet.docx');

new content was insert before last line.

answered Apr 22, 2015 at 14:30

Irq Mishell's user avatar

The easiest way to figure out an outline for the actual code is to record a macro in Word for that specific action. Then you can modify the generated code to suit different syntax(s) of VB, VB.NET, C# etc.

The code snippet below demonstrates the usage for a VB.NET application:

Imports wordNmSpace = Microsoft.Office.Interop.Word
' Create an object for the application instance
objWord = CreateObject("Word.Application")

' Create a reference of the selection object within Word
objSelection = objWord.Selection

' Now comes the part where you move selection position to the end of document
objSelection.endof(wordNmSpace.WdUnits.wdStory, wordNmSpace.WdMovementType.wdMove)

Hope this helps.

Jonnus's user avatar

Jonnus

2,9782 gold badges23 silver badges33 bronze badges

answered Oct 29, 2015 at 11:58

Arpit Buddhiwant's user avatar

To change cursor position at the end of the current document in a C# Word Add-In VSTO :

this.Application.ActiveDocument.Range(
this.Application.ActiveDocument.Content.End-1,
this.Application.ActiveDocument.Content.End-1).Select();

See How to: Programmatically Define and Select Ranges in Documents

answered Aug 21, 2015 at 13:43

hayj's user avatar

hayjhayj

1,14413 silver badges21 bronze badges

Try this :

int lNumberOfPages = 
  _WordDoc.ComputeStatistics(Word.WdStatistic.wdStatisticPages, false);

WordApp.Selection.GoTo(Word.WdGoToItem.wdGoToPage,WordApp.WdGoToDirection.wdGoToLast, lNumberOfPages);

PM.'s user avatar

PM.

1,7351 gold badge31 silver badges38 bronze badges

answered Oct 3, 2017 at 2:03

Amir Keynia's user avatar

for net office:

mydoc.Range(GlobalClass.mydoc.Content.End-1 , mydoc.Content.End - 1).Select();

answered Feb 10, 2019 at 11:27

Ehsan.B's user avatar

0

Редактирование документов Word из кода VBA Excel. Добавление и форматирование текста. Объект Word.Range, свойство Text, методы InsertAfter и InsertBefore.

Работа с Word из кода VBA Excel
Часть 3. Редактирование документов Word
[Часть 1] [Часть 2] [Часть 3] [Часть 4] [Часть 5] [Часть 6]

Добавление текста в новый документ

Основные объекты, использующиеся в VBA Word для определения места вставки, добавления и форматирования текста – это Selection (выделение), Range (диапазон) и Bookmark (закладка).

Selection и Range позволяют заполнять текстом новые документы или редактировать существующие. Закладки можно использовать для вставки изменяемых реквизитов в шаблоны различных документов: договоры, акты, справки.

Объект Range имеет преимущество перед объектом Selection, так как он может быть создан только программно и не зависит от действий пользователя. Если для вставки и форматирования текста будет использоваться объект Selection, а пользователь во время работы программы просто поставит курсор в другое место документа, результат будет непредсказуем.

Word.Range кардинально отличается от объекта Range в Excel. В приложении Word он представляет из себя набор из одного или множества символов. А также он может вообще не содержать ни одного символа, а быть указателем ввода текста (виртуальным курсором).

Объект Range возвращается свойством Range других объектов приложения Word: Document, Selection, Bookmark, Paragraph, Cell (объект Table).

Вставка текста без форматирования

Если текст вставляется без форматирования, достаточно одной строки кода (myDocument – это переменная):

  • Вставка текста с заменой имеющегося: myDocument.Range.Text = "Вставляемый текст"
  • Добавление текста после имеющегося: myDocument.Range.InsertAfter "Добавляемый текст"
  • Добавление текста перед имеющимся: myDocument.Range.InsertBefore "Добавляемый текст"

Методами InsertAfter и InsertBefore можно вставить текст и на пустую страницу, также, как с помощью свойства Text. Перейти на новый абзац и начать предложение с красной строки можно с помощью ключевых слов vbCr (vbNewLine, vbCrLf) и vbTab.

Вставка текста с форматированием

Для форматирования отдельных участков текста необходимо указать диапазон символов, входящих в этот участок. Здесь нам также поможет объект Range, которому можно задать любой набор символов, содержащихся в документе Word.

Синтаксис присвоения диапазона символов объекту Range:

myDocument.Range(Start:=n, End:=m)

‘или без ключевых слов Start и End

myDocument.Range(n, m)

  • myDocument – переменная;
  • n – номер точки перед начальным символом;
  • m – номер точки после конечного символа.

Счет точек вставки начинается с нуля. Знаки переноса строки, возврата каретки и табуляции учитываются как отдельные символы. 0 – это для объекта Word.Range виртуальная точка вставки на пустом документе, 1 – точка между первым и вторым символом, 2 – точка между вторым и третьим символом и т.д.

На пустом документе объекту Range можно присвоить только виртуальную точку вставки:
myDocument.Range(Start:=0, End:=0)

Первый символ в документе с текстом:
myDocument.Range(Start:=0, End:=1)

Диапазон с 11 по 20 символ:
myDocument.Range(Start:=10, End:=20)

Реальная точка вставки (курсор) принадлежит объекту Selection, который создается вручную или программно с помощью метода Select.

Вставка курсора в начало документа:
myDocument.Range(Start:=0, End:=0).Select

Эта строка вставит курсор между пятым и шестым символами:
myDocument.Range(Start:=5, End:=5).Select

Вставка курсора в конец документа:
myDocument.Range(.Range.Characters.Count - 1, .Range.Characters.Count - 1).Select

Ссылку на объект Range можно присвоить переменной, но при форматировании ее придется каждый раз переопределять и код получится длиннее. Пример присвоения ссылки объектной переменной:

Dim myRange As Word.Range

Set myRange = myDocument.Range(Start:=0, End:=20)

Для Range(Start:=0, End:=20) в документе должно быть как минимум 20 символов.

Однострочные примеры редактирования и форматирования текста

Вставка дополнительного текста внутри имеющегося после заданной точки:
myDocument.Range(Start:=10, End:=10).InsertAfter "Вставляемый текст"

Новый абзац с красной строки (предыдущая строка должна заканчиваться символом возврата каретки или переноса строки):
myDocument.Range.InsertAfter vbTab & "Красная строка"

Присвоение шрифту заданного диапазона зеленого цвета:
myDocument.Range(Start:=10, End:=65).Font.ColorIndex = wdGreen

Меняем обычное начертание на курсив:
myDocument.Range(Start:=10, End:=65).Font.Italic = True

Указываем размер шрифта:
myDocument.Range(Start:=10, End:=65).Font.Size = 22

Применение стандартных стилей:
myDocument.Range(Start:=0, End:=16).Style = "Заголовок 1"

Если вас заинтересуют другие команды форматирования текста, запишите их макрорекордером в VBA Word и примените к объекту Range.

Пример 1
Добавление текста в новый документ без форматирования:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

Sub Primer1()

On Error GoTo Instr

Dim myWord As New Word.Application, _

myDocument As Word.Document

Set myDocument = myWord.Documents.Add

myWord.Visible = True

With myDocument

.Range.Text = «Заголовок по центру» & vbCr

.Range(Start:=0, End:=19).ParagraphFormat.Alignment _

  = wdAlignParagraphCenter

.Range.InsertAfter _

  vbTab & «Первый абзац с красной строки» & vbCr & _

  «Второй абзац не с красной строки» & vbCr & _

  vbTab & «Третий абзац с красной строки»

End With

Set myDocument = Nothing

Set myWord = Nothing

Exit Sub

Instr:

If Err.Description <> «» Then

  MsgBox «Произошла ошибка: « & Err.Description

End If

If Not myWord Is Nothing Then

  myWord.Quit

  Set myDocument = Nothing

  Set myWord = Nothing

End If

End Sub

Пример 2
Добавление текста в новый документ с форматированием:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

Sub Primer2()

On Error GoTo Instr

Dim myWord As New Word.Application, _

myDocument As Word.Document

Set myDocument = myWord.Documents.Add

myWord.Visible = True

With myDocument

.Range.Text = «Заголовок по центру» & vbCr

.Range(Start:=0, End:=19).Style = «Заголовок»

.Range(Start:=0, End:=19).ParagraphFormat.Alignment _

  = wdAlignParagraphCenter

.Range.InsertAfter «Заголовок 1 не по центру» & vbCr

.Range(Start:=20, End:=44).Style = «Заголовок 1»

.Range.InsertAfter vbTab & «Шрифт по умолчанию « _

  & «с красной строки» & vbCr

.Range.InsertAfter «Зеленый курсив, размер 20»

.Range(Start:=82, End:=107).Font.Italic = True

.Range(Start:=82, End:=107).Font.Size = 20

.Range(Start:=82, End:=107).Font.ColorIndex = wdGreen

End With

Set myDocument = Nothing

Set myWord = Nothing

Exit Sub

Instr:

If Err.Description <> «» Then

  MsgBox «Произошла ошибка: « & Err.Description

End If

If Not myWord Is Nothing Then

  myWord.Quit

  Set myDocument = Nothing

  Set myWord = Nothing

End If

End Sub

Вы можете запустить эти примеры в редакторе VBA Excel на своем компьютере и посмотреть результаты.

2 / 2 / 0

Регистрация: 11.09.2006

Сообщений: 7

1

12.09.2006, 14:26. Показов 17776. Ответов 6


Студворк — интернет-сервис помощи студентам

Как в word-е перейти в начало определенной строки, если положение курсора не известно?



0



0 / 0 / 0

Регистрация: 25.05.2011

Сообщений: 27

12.09.2006, 16:10

2

Вопрос не ясен. Перейти в начало какой строки. Если в начало текущей то нажав клавишу «Home» Вы получите счастье и Вам даже ВБА не нужен. Если в начало какой то определенной, то тут надо думать и предоставленной информации явно не достаточно.
С уважением,
Алесандр



0



2 / 2 / 0

Регистрация: 11.09.2006

Сообщений: 7

12.09.2006, 17:06

 [ТС]

3

Задача в следующем, нужно добавить таблицу на N-ой строчке листа, используя VBA. Я знаю, как добавить таблицу, как заполнить, но таблица добавляется там, где курсор, поэтому и возник вопрос. Где курсор и как его переместить на другое место? Может, есть другой способ вставить таблицу?



0



игорий

2 / 2 / 0

Регистрация: 16.04.2012

Сообщений: 24

12.09.2006, 18:42

4

переместить курсор на интересующую строку можно этим кодом:

Visual Basic
1
2
3
4
5
6
7
8
Dim WordApp As Object
Set WordApp = CreateObject("word.application")
WordApp.Visible = True
Set DocWord = WordApp.Documents.Open("C:    est.doc")
DocWord.Activate
 
x = 16 'номер интересующей строки
DocWord.Application.Selection.GoTo(3, , x, "").Select



1



2 / 2 / 0

Регистрация: 11.09.2006

Сообщений: 7

12.09.2006, 20:21

 [ТС]

5

Спасибо! Все работает.
Скажите, пожалуйста, а почему в скобках, первый параметр 3, если я правильно понял из хелпа VBA, 3 это конец страницы? Без этого парамета добавление происходит в первую строку.



0



2 / 2 / 0

Регистрация: 16.04.2012

Сообщений: 24

12.09.2006, 22:42

6

на сколько я понял из опыта — первый параметр это описание того что именно будет считать выражение. так если указать единицу — будут считаться страницы а если указать 3 — соответственно строки.

существует возможность «посчитать» любой элемент документа и выделить соответствующий. нужно указывать только соответствующий параметр…

например если в документе 4 таблицы , можно указав wdGoToTable в качестве первого параметра и 3 в качестве третьего — вы соответственно выберем третью таблицу

вот как то так…



1



2 / 2 / 0

Регистрация: 11.09.2006

Сообщений: 7

13.09.2006, 13:41

 [ТС]

7

Я немного разобрался, большое спасибо.
Вот к чему я пришел: <B>GoTo(What, Which, Count, Name)</B>
<B>What</B> может быть:
wdGoToBookmark (-1) – перейти к закладке;
wdGoToSection (0) — перейти к секции;
wdGoToPage (1) — перейти к листу;
wdGoToTable (2) — перейти к таблице;
wdGoToLine (3) — перейти к строке;
wdGoToFootnote (4) — перейти к сноске;
wdGoToEndnote (5) — перейти к примечанию;
wdGoToComment (6) — перейти к комментарию;
wdGoToField (7) — перейти к полю;
wdGoToGraphic (8) – перейти к графику;
wdGoToObject (9) – перейти к объекту;
wdGoToEquation (10) — перейти к абзацу;
wdGoToHeading (11) — перейти к заголовку;
wdGoToSpellingError (13) — перейти к орфографической ошибке;
wdGoToGrammaticalError (14) — перейти к грамматической ошибке.
<B>Which</B> тоже может иметь разные значиния (как работает не знаю)
<B>Count</B> номер закладки, секции и т.д.
<B>Name</B> имя закладки, секции и т.д. (как задать имя, например, абзаца я, пока, не знаю)
ЗЫ: может кому-нибудь еще будет полезен этот топик, поэтому и написал.



2



Asked
6 years, 4 months ago

Viewed
3k times

How to move the cursor to the beginning of the page? Using VBA Macro.

asked Nov 22, 2016 at 12:43

Albert Diago's user avatar

You can move the selection to the beginning of the current page using the following workaround (assuming you are starting from a collapsed selection):

If Selection.Range.Information(wdActiveEndPageNumber) = 1 Then
    Selection.GoTo wdGoToPage, wdGoToNext
    Selection.GoTo wdGoToPage, wdGoToPrevious
Else
    Selection.GoTo wdGoToPage, wdGoToPrevious
    Selection.GoTo wdGoToPage, wdGoToNext
End If

answered Nov 22, 2016 at 13:46

Dirk Vollmar's user avatar

Dirk VollmarDirk Vollmar

171k53 gold badges256 silver badges313 bronze badges

Понравилась статья? Поделить с друзьями:
  • Vba word копировать документ
  • Vba word копировать весь текст
  • Vba word конец файла
  • Vba word конец текста
  • Vba word количество таблиц