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.

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



Формулировка задачи:

Есть вордовский документ, необходимо определить его начало и спустить текст вниз…
Подскажите как сделать?

Код к задаче: «Word: определить начало в документе»

textual

With ActiveDocument.Paragraphs(1)
  .SpaceBefore = .SpaceBefore + 20
End With

Полезно ли:

9   голосов , оценка 4.111 из 5

Мы манипулируем нашими документами Word 2007 из .Net с помощью Word Interop. В основном делаю что-то с полями, как в:

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

Это оставляет последнее поле в документе выбранным.

Итак, для наглядности мы хотели бы поместить курсор в конец документа (или даже начало было бы в порядке).

Поиск ответа в Google не вызывает особых проблем … ближайший, который я могу найти, похоже, предполагает, что нам нужно задействовать диапазоны или закладки. Для объекта Document существует метод GoTo, но ни один из предлагаемых им параметров WdGoToItem не является полезным.

Нет ли простого способа просто отправить курсор в конец (или начало) документа?

Изменить

Частично моя проблема заключалась в том, что мне не нравилось оставлять выбранное последнее поле. Теперь понял, что могу

f.Unlink

Чтобы удалить mergefield и просто оставить текст поля в виде обычного текста. Что более аккуратно, независимо от того, перемещаем ли мы также курсор

9 ответов

Лучший ответ

@ Александр Кожевников: Спасибо за вашу помощь, потому что вы направили меня на правильный путь. Однако я обнаружил, что мне нужно применить .GoTo к объекту Word Selection, а не к документу. Как в:

    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)


13

hawbsl
20 Окт 2009 в 12:45

Вот как это выглядит на 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);

Думаю, в VB.Net будет еще проще, поскольку он поддерживает необязательные параметры.


8

Alexander Kojevnikov
20 Окт 2009 в 03:49

Я не уверен, что использую ту же среду, что и вы, но чтобы перейти к началу или концу документа, вот что мне подходит:

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

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


3

Fuhrmanator
21 Фев 2014 в 07:44

Я использую модуль Word_TLB в Delphi с объектом приложения — Word.Application

Следующим образом:

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

обычно в конце слова в документе :

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

Когда я использую

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

Новый контент был вставлен перед последней строкой.


2

Irq Mishell
23 Апр 2015 в 08:52

Самый простой способ выяснить схему фактического кода — записать макрос в Word для этого конкретного действия. Затем вы можете изменить сгенерированный код для соответствия другому синтаксису (синтаксисам) VB, VB.NET, C # и т. Д.

Приведенный ниже фрагмент кода демонстрирует использование приложения VB.NET:

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)

Надеюсь это поможет.


1

Jonnus
29 Окт 2015 в 15:21

Чтобы изменить положение курсора в конце текущего документа в VSTO надстройки C # Word:

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

См. Как: программное определение и выбор диапазонов в документах


0

hayj
21 Авг 2015 в 16:43

Попробуй это :

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

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

Для сетевого офиса:

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


0

Ehsan.B
10 Фев 2019 в 14:27

  • Добро пожаловать на Форум по VBA, Excel и Word.

  • Войти


  • Регистрация

 

Форум по VBA, Excel и Word

Почта для связи: Box1100@yandex.ru

14 апреля 2023, 20:33


Главное меню

Главное меню

  • Начало

  • Поиск

  • Форум по VBA, Excel и Word

  • Word

  • Макросы в Word

  • Word VBA Макросы: Установка курсора в любом указанном абзаце.

Автор Game, 03 сентября 2019, 09:57

Печать

Вниз
Страницы1

Действия пользователя

Game

  • гость
  • Записан

Word VBA Макросы: Установка курсора в любом указанном абзаце.




03 сентября 2019, 09:57


Каким образом можно можно поставить курсор в начале определенного абзаца?
Например. У меня 10 абзацев, но кол-во строк в этих абзацах разные. Необходимо поставить курсор в начале 3 абзаца.



Администратор

  • Administrator
  • Сообщения: 2,252
  • Записан

Re: Word VBA Макросы: Установка курсора в любом указанном абзаце.

#1




03 сентября 2019, 10:07


Макрос

Sub Макрос()

        Dim doc As Document

            ‘ Присваиваем активному файлу имя «doc».
        ‘ Может быть так будет удобнее читать и писать код.
    Set doc = ActiveDocument

        ‘ Установка курсора в начало третьего абзаца.
    doc.Range(doc.Paragraphs(3).Range.Start, doc.Paragraphs(3).Range.Start).Select

End Sub

[свернуть]

Или можно ещё так установить. Функционал тот же, просто разный стиль написания кода:

Макрос

Sub Макрос()

        With ActiveDocument
        .Range(.Paragraphs(3).Range.Start, .Paragraphs(3).Range.Start).Select
    End With

End Sub

[свернуть]


Game

  • гость
  • Записан

Re: Word VBA Макросы: Установка курсора в любом указанном абзаце.

#2




03 сентября 2019, 10:19


Спасибо. Все работает.


Печать

Вверх
Страницы1

Действия пользователя

  • Форум по VBA, Excel и Word

  • Word

  • Макросы в Word

  • Word VBA Макросы: Установка курсора в любом указанном абзаце.

Действия пользователя

Печать

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