Vba word конец файла

aski4

0 / 0 / 0

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

Сообщений: 2

1

Как правильно определить конец документа для работы с ним?

05.05.2020, 12:50. Показов 4007. Ответов 3

Метки vba word (Все метки)


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

Сразу два вопроса:

1) Была тут тема Как определить конец документа в Word?. Пытался подробным способом выделить и удалить последнюю страницу.

C#
1
2
3
doc.Application.Selection.GoTo(1, ref oMissing, page_nmb, "");
doc.Range(doc.Application.Selection.Start, doc.Application.Selection.Expand(Microsoft.Office.Interop.Word.WdUnits.wdStory)).Select();
doc.Application.Selection.Delete();

(Извиняюсь что код на шарпе, а не vba, не думаю что это сильно влияет на суть вопроса. Ответ приветствуется на любом языке.)
Таким способом последняя страница на которой абзац начинается в начале страницы — удаляется нормально. Если же абзац переходит с предыдущей страницы, содержимое последней страницы удаляется, а пустая страница остается. Как удалить страницу полностью?

2) Примерно таким же способом пытаюсь перейти на конец документа и добавить пустую страницу

C#
1
2
3
4
5
doc.Application.Selection.GoTo(1, ref oMissing, page_nmb, "");
//doc.Application.Selection.EndOf(Microsoft.Office.Interop.Word.WdUnits.wdStory, Microsoft.Office.Interop.Word.WdMovementType.wdMove);
//doc.Application.Selection.MoveEnd(Microsoft.Office.Interop.Word.WdUnits.wdStory);
doc.Application.Selection.EndKey(Microsoft.Office.Interop.Word.WdUnits.wdStory, Microsoft.Office.Interop.Word.WdMovementType.wdMove);
doc.Application.Selection.InsertBreak(Microsoft.Office.Interop.Word.WdBreakType.wdPageBreak);

Добавляется две пустых страницы вместо одной. Как правильно добавить одну страницу в конец документа?



0



amd48

779 / 461 / 79

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

Сообщений: 1,242

Записей в блоге: 4

06.05.2020, 07:33

2

не совсем понятно, что именно надо получить. количество листов в документе?
есть просто параметр документа:

Visual Basic
1
MsgBox ActiveDocument.Content.Information(wdActiveEndAdjustedPageNumber)

или, если у вас приложуха Word запущена, то почему просто не перейти к концу документа?

Visual Basic
1
2
Selection.EndKey Unit:=wdStory
MsgBox Selection.Information(wdActiveEndPageNumber)

Добавлено через 7 минут
2. пустая страница добавляется так:

Visual Basic
1
Selection.InsertNewPage

а вы добавляете разрыв страницы InsertBreak



1



aski4

0 / 0 / 0

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

Сообщений: 2

06.05.2020, 09:35

 [ТС]

3

amd48

2. пустая страница добавляется так:

PureBasic
1
Selection.InsertNewPage

Такая вставка новой страницы работает, спасибо.

Количество страниц, не совсем то что мне нужно определить, для определения количества я использую:

C#
1
doc.ActiveWindow.ActivePane.Pages.Count;

Остался вопрос: как удалить последнюю страницу со всем содержимым?



0



amd48

779 / 461 / 79

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

Сообщений: 1,242

Записей в блоге: 4

06.05.2020, 13:36

4

Цитата
Сообщение от aski4
Посмотреть сообщение

как удалить последнюю страницу со всем содержимым?

Ну удаляется не страница, а текст. Если страница добавлена разрывом страниц, то это символ разрыва.
как-то так:

Visual Basic
1
2
3
4
5
6
7
8
    Selection.EndKey Unit:=wdStory                      'переходим в конец документа
    With Selection.Find
        .Text = "^m"                                    'ищем символ разрыва страницы
        .Forward = False                                'отсюда и назад. т.е. последний в документе
    End With
    Selection.Find.Execute
    Selection.EndKey Unit:=wdStory, Extend:=wdExtend    'выделяем отсюда и до конца
    Selection.Delete                                    'удаляем

Добавлено через 8 минут
Да. И особенность разрыва в том, что он находится на предыдущей странице. А если их в документе несколько? Можно после поиска добавить проверку: если курсор на предпоследнем листе (количество листов минус 1), то это тот самый разрыв — можно удалить



0



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...

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

Подскажите как
1) определить конец документа в Word (например, цикл пока не конец документа).
2) как выбрать от определенного места до конца документа (типа
Selection.MoveEndUntil Cset:=’конец документа’

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

textual

Selection.EndKey Unit:=wdStory, Extend:=wdExtend

Полезно ли:

11   голосов , оценка 3.909 из 5

I have recorded a simple macro to find the word «Quantity», go to the end of that line and insert a carriage return. I need to repeat it to the end of the document and quit, or else I’ll have an infinite loop.

The code:

     Selection.Find.ClearFormatting
     With Selection.Find
    .Text = "Quantity:"
    .Replacement.Text = ""
    .Forward = True
    .Wrap = wdFindContinue
    .Format = False
    .MatchCase = True
    .MatchWholeWord = False
    .MatchWildcards = False
    .MatchSoundsLike = False
    .MatchAllWordForms = False
End With
Selection.Find.Execute
Selection.EndKey Unit:=wdLine
Selection.TypeParagraph  

Martijn Pieters's user avatar

asked May 29, 2014 at 21:49

user3689278's user avatar

2

Change you code to this, note the use of wdFindStop.

Selection.Find.ClearFormatting
     With Selection.Find
    .Text = "Quantity:"
    .Replacement.Text = ""
    .Forward = True
    .Wrap = wdFindStop
    .Format = False
    .MatchCase = True
    .MatchWholeWord = False
    .MatchWildcards = False
    .MatchSoundsLike = False
    .MatchAllWordForms = False
End With

do while Selection.Find.Execute = true
   Selection.EndKey Unit:=wdLine
    Selection.TypeParagraph  
loop

If you have the type of documents this can fail on you can use the Selection.Start by
replacing the loop like this:

Dim lastPos As Long
lastPos = -1
Do While Selection.Find.Execute = True
    If lastPos > Selection.Start Then Exit Do
    Selection.EndKey Unit:=wdLine
    Selection.TypeParagraph
Loop

answered Jun 3, 2014 at 1:50

user2903089's user avatar

user2903089user2903089

2831 silver badge10 bronze badges

Add Selection.Find.Execute Replace:=wdReplaceAll after your End with

answered Jul 22, 2015 at 4:38

Dave F's user avatar

Dave FDave F

15114 bronze badges

Like this post? Please share to your friends:
  • Vba word конец текста
  • Vba word количество таблиц
  • Vba word количество страницам
  • Vba word количество страниц в документе
  • Vba word количество столбцов