Visual basic word document

Создание нового документа Word или открытие существующего из кода VBA Excel. Методы Documents.Add и Documents.Open. Сохранение и закрытие документа.

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

Новый документ Word создается из кода VBA Excel с помощью метода Documents.Add:

Sub Test1()

Dim myWord As New Word.Application

Dim myDocument As Word.Document

Set myDocument = myWord.Documents.Add

myWord.Visible = True

End Sub

Переменную myDocument можно объявить с типом Object, но тогда не будет ранней привязки к типу Word.Document и подсказок при написании кода (Auto List Members).

Открытие существующего документа

Существующий документ Word открывается из кода VBA Excel с помощью метода Documents.Open:

Sub Test2()

Dim myWord As New Word.Application

Dim myDocument As Word.Document

Set myDocument = _

myWord.Documents.Open(«C:Документ1.docx»)

myWord.Visible = True

End Sub

Замените в этой процедуре строку «C:Документ1.docx» на адрес своего файла.

Подключение к открытому документу

Присвоение переменной ссылки на существующий экземпляр Word.Application осуществляется в VBA Excel с помощью функции GetObject:

Sub Test3()

Dim myWord As Object, myDoc As Word.Document

On Error GoTo Instr

    Set myWord = GetObject(, «Word.Application»)

    Set myDoc = myWord.Documents(«Документ1.docx»)

    myDoc.Range.InsertAfter «Добавляем новый текст, подтверждающий подключение к открытому документу.»

Exit Sub

Instr:

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

End Sub

Если открытого приложения Word нет, выполнение функции GetObject приведет к ошибке. Также произойдет ошибка, если не будет найден указанный документ (в примере — «Документ1.docx»).

Сохранение и закрытие документа

Сохранение нового документа

Чтобы сохранить из кода VBA Excel новый документ Word, используйте метод SaveAs2 объекта Document:

myDocument.SaveAs2 («C:Документ2.docx»)

Замените «C:Документ2.docx» на путь к нужному каталогу с именем файла, под которым вы хотите сохранить новый документ.

Сохранение изменений в открытом документа

Сохраняйте изменения в существующем документе с помощью метода Document.Save или параметра SaveChanges метода Document.Close:

‘Сохранение изменений документа

myDocument.Save

‘Сохранение изменений документа

‘при закрытии

myDocument.Close ‘по умолчанию True

myDocument.Close True

myDocument.Close wdSaveChanges

‘Закрытие документа без

‘сохранения изменений

myDocument.Close False

myDocument.Close wdDoNotSaveChanges

Закрытие любого сохраненного документа

Метод Document.Close закрывает документ, но не приложение. Если работа с приложением закончена, оно закрывается с помощью метода Application.Quit.

Содержание

  • 1 Add a word document
  • 2 Close a document
  • 3 Generating Word ata from an Excel VBA program
  • 4 Load contact table from Access and create letter in Word
  • 5 Open an Existing Document
  • 6 Save a document
  • 7 Save Changes to a Document
  • 8 To close a specific document, you can close the active document or you can specify a document name:
  • 9 To create a new document that uses a specific template, use this:
  • 10 To save a document with a new name, use the SaveAs method

Add a word document

   <source lang="vb">

Sub wordDoc()

   Dim WordApp As Object
   Set WordApp = CreateObject("Word.Application")
   With WordApp
       .Documents.Add
   End With

End Sub

</source>
   
  

Close a document

   <source lang="vb">

Sub exitFor()

   Dim Doc As Document
   For Each Doc In Documents
       If Doc.Name = "Document1" Then Exit For
       Doc.Close
   Next Doc

End Sub

</source>
   
  

Generating Word ata from an Excel VBA program

   <source lang="vb">

Sub MakeMemos()

   Dim WordApp As Object
   Set WordApp = CreateObject("Word.Application")
   
   For i = 1 To 3
       Application.StatusBar = "Processing Record " & i
       SaveAsName = ThisWorkbook.Path & "test.doc"
       With WordApp
           .Documents.Add
           With .Selection
               .Font.Size = 14
               .Font.Bold = True
               .ParagraphFormat.Alignment = 1
               .TypeText Text:="M E M O R A N D U M"
               .TypeParagraph
               .TypeParagraph
               .Font.Size = 12
               .ParagraphFormat.Alignment = 0
               .Font.Bold = False
               .TypeText Text:="Date:" & vbTab & Format(Date, "mmmm d, yyyy")
               .TypeParagraph
               .TypeText Text:="To:" & vbTab & " Manager"
               .TypeParagraph
               .TypeText Text:="From:" & vbTab & _
                  Application.userName
               .TypeParagraph
               .TypeParagraph
               .TypeText "text"
               .TypeParagraph
               .TypeParagraph
               .TypeText Text:="Units Sold:" & vbTab & "asdf"
               .TypeParagraph
               .TypeText Text:="Amount:" & vbTab & Format(1000, "$#,##0")
           End With
               .ActiveDocument.SaveAs FileName:=SaveAsName
               .ActiveWindow.Close
       End With
   Next i
   WordApp.Quit
   Set WordApp = Nothing
   Application.StatusBar = ""
   MsgBox " memos were created and saved in " & ThisWorkbook.Path

End Sub

</source>
   
  

Load contact table from Access and create letter in Word

   <source lang="vb">

Sub ControlWord()

   Dim objWord As New Word.Application
   Dim rsContacts As New ADODB.Recordset
   Dim strLtrContent As String
   rsContacts.ActiveConnection = CurrentProject.Connection
   rsContacts.Open "tblContacts"
   
   objWord.Documents.Add
   
   Do While Not rsContacts.EOF
     strLtrContent = rsContacts("FirstName") & " " & rsContacts("LastName")
     strLtrContent = strLtrContent & rsContacts("Address") & vbCrLf
     strLtrContent = strLtrContent & rsContacts("City") & ", " & rsContacts("Region")
     strLtrContent = strLtrContent & "  " & rsContacts("PostalCode") 
     strLtrContent = strLtrContent & "Dear " & rsContacts("FirstName") & " "
     strLtrContent = strLtrContent & rsContacts("LastName") & ":" 
   
       objWord.Selection.EndOf
       objWord.Selection.Text = strLtrContent
   
       objWord.Selection.EndOf
       objWord.Selection.InsertBreak
       
       rsContacts.MoveNext
   Loop
   objWord.Visible = True
   objWord.PrintPreview = True

End Sub

</source>
   
  

Open an Existing Document

   <source lang="vb">

Sub Main()

   Dim wdApp As Word.Application
   
   Set wdApp = GetObject(, "Word.Application")
   wdApp.Documents.Open Filename:="C:Arrays.docx", ReadOnly:=True, AddtoRecentFiles:=False

End Sub

</source>
   
  

Save a document

   <source lang="vb">

Sub WordLateBound()

   Dim objWord As Object 
   Dim objDoc As Object 
   Set objWord = CreateObject("Word.Application") 
   Set objDoc = objWord.Documents.Add 
   objDoc.SaveAs "C:testdoc2.doc" 
   objDoc.Close 
   Set objDoc = Nothing 
   Set objWord = Nothing 

End Sub

</source>
   
  

Save Changes to a Document

   <source lang="vb">

Sub main()

   Dim wdApp As Word.Application
   
   Set wdApp = GetObject(, "Word.Application")
   wdApp.Documents.Save

End Sub

</source>
   
  

To close a specific document, you can close the active document or you can specify a document name:

   <source lang="vb">

Sub main()

   Dim wdApp As Word.Application
   Set wdApp = GetObject(, "Word.Application")
   wdApp.ActiveDocument.Close
   "or
   wdApp.Documents("Arrays.docx").Close

End Sub

</source>
   
  

To create a new document that uses a specific template, use this:

   <source lang="vb">

Sub add()

   Dim wdApp As Word.Application
   
   Set wdApp = GetObject(, "Word.Application")
   wdApp.Documents.Add Template:="Contemporary Memo.dot"

End Sub

</source>
   
  

To save a document with a new name, use the SaveAs method

   <source lang="vb">

Sub Main()

   Dim wdApp As Word.Application
   Set wdApp = GetObject(, "Word.Application")
   wdApp.ActiveDocument.SaveAs "C:MemoTest.docx"

End Sub

</source>

Using Excel VBA to read and write Microsoft Word documents

These examples are written and tested in Excel 2003.

Create, Write and Close Word Document
Read and Append

Create, Write and Close Word Document

The following code illustrates the use of Excel VBA to create a Microsoft Word Document and save it to disk.
This script will create a document in your My Documents folder.

'In Tools > References, add reference to &quot;Microsoft Word XX.X Object Library&quot; before running.
Option Explicit

Sub CreateNewWordDoc()
    
    Dim wdApp As Word.Application
    Dim wdDoc As Word.Document
    Set wdApp = CreateObject("Word.Application")
    Dim myFile As String
    
    'Alternatively, we can use Late Binding
    'Dim wdApp As Object
    'Dim wdDoc As Object
    'Set wdApp = CreateObject("word.Application")
        
    wdApp.Visible = True
    Set wdDoc = wdApp.Documents.Add
    
    ' define a place to put file
    myFile = Environ("UserProfile") & "My Documents" & "MyWordDoc.docx"
    
    ' or like this
    myFile = Environ("UserProfile") & "Documents" & "MyWordDoc.docx"

    ' have to wrap name in quotes here because directory contains a space
    If Dir("""&myFile&""") <> "" Then
        ' kill = delete existing file
        Kill """&myFile&"""
    End If

    With wdDoc
        .Content.InsertAfter "Hello World"
        .Content.InsertParagraphAfter
        .SaveAs myFile
        .Close
    End With
    
    wdApp.Quit
    Set wdDoc = Nothing
    Set wdApp = Nothing

End Sub


Some VBA Vocabulary

Option Explicit
When Option Explicit On or Option Explicit appears in a file, you must explicitly declare all variables by using the Dim or ReDim statements. If you try to use an undeclared variable name, an error occurs at compile time. The Option Explicit Off statement allows implicit declaration of variables. This statement
reduces risk of error by mis-typing variable names.

Word.Application
Represents the Microsoft Word application. The Application object includes properties and methods that return top-level objects.
To use Automation to control Word from another application, use the Microsoft Visual Basic CreateObject or GetObject function to return a Word Application object.

Word.Document
Represents a Word document. The Document object is a member of the Documents collection. The Documents collection contains all the Document objects that are currently open in Word.

InsertAfter
Inserts the specified text at the end of a range or selection. After this method is applied, the range or selection expands to include the new text.

Kill Deletes files from a disk.

DirThe Microsoft Excel DIR function returns the first filename that matches the pathname and attributes specified. To retrieve additional filenames that match pathname and attributes, call DIR again with no arguments.

Early and Late Binding

An object is early bound when it is assigned to a variable declared to be of a specific object type. By contrast, an object is late bound when it is assigned to a variable declared to be of type Object. Objects of this type can hold references to any object, but lack many of the advantages of early-bound objects

Early binding: The first step in using early binding is to ensure that the compiler «knows» about the object to which you want to bind. If you are working with a Excel or Word, then the controls in the toolbox are all known, or intrinsic, objects, and you can create references to them without any concern.

Late Binding: With late binding, the code does not make an explicit reference to the type of object when the variable is declared. Instead, it will simply use the «Object» type.

Read and Append to a Microsoft Word Document

The following code illustrates the use of Excel VBA to read and appaend to a Microsoft Word Document.
This script will trad a document in your My Documents folder.

'In Tools > References, add reference to "Microsoft Word XX.X Object Library" before running.
Option Explicit

Sub CreateNewWordDoc()
    
    Dim wdApp As Word.Application
    Dim wdDoc As Word.Document
    Set wdApp = CreateObject("Word.Application")
    Dim myFile As String
    
    'Alternatively, we can use Late Binding
    'Dim wdApp As Object
    'Dim wdDoc As Object
    'Set wdApp = CreateObject("word.Application")
    
    myFile = Environ("UserProfile") & "/My Documents/" & "MyWordDoc.docx"
    Set wdDoc = wdApp.Documents.Open(myFile)
    wdApp.Visible = True
    
    With wdDoc
        
        .Content.InsertAfter "Hello World"
        .Content.InsertParagraphAfter

    End With
    
End Sub

word vba tutorial

Welcome to the Word VBA Tutorial. VBA is a great tool not only to be leveraged in MS Excel. Often it is worth to save some time doing repeatable tasks by adopting some VBA macros in Word or PowerPoint too. Today I wanted to focus a little bit on starting you off in Word VBA macro programming.

vba word tutorialWhen moving to macro programming in Word VBA you will stumble upon issues you would normally not expect in Excel. Lets take the example of moving around the Word file – in Excel you have spreadsheets which are easy to navigate around. In Word, however, you have a lot of different content e.g. text, objects like images and charts, tables etc. Navigating around Word file in VBA is the greatest challenge you will face. Today I would like to focus on that and other frequently used features in Word VBA. So let’s kick off this Word VBA Tutorial.

Starting your journey with programming in Visual Basic for Applications (VBA)? Start with my VBA Tutorial.

Word VBA is identical to Excel VBA – be sure to leverage the VBA Cheat Sheet

VBA Word Navigating

Let’s start with adding content to the most common places the start and end of a Word document in VBA. Know if you Google for this you will get tons of non-sense methods of navigating around Word files. I was truly amazed at how poorly it is documented.

Beginning and End of the Word Document

Go to the Beginning of a Word Document:

'Start - add text to the beginning of the Word Document
Dim startMark As Range
Set startMark = ActiveDocument.Range(0, 0)
startMark.Text = "This is the start of the document"

Go to the End of a Word Document:

'End - add text to the end of the Word Document
Dim endMark As Range
Set endMark = ActiveDocument.Range(Len(ActiveDocument.Range))
endMark.Text = "This is the end of the document"

Finding and replacing text in a Word Document with VBA

Finding and replacing text are basic functions that you will probably need to leverage every now and then.

'Find and print text in MsgBox
Dim selectText As Range
Set selectText = ActiveDocument.Content
selectText.Find.Execute "Hello"
If selectText.Find.Found Then
  MsgBox selectText.Text
End If
'Find and replace all instances of a specific text
Dim replaceText As Range
Set replaceText = ActiveDocument.Content
replaceText.Find.Execute FindText:="Hello", ReplaceWith:="Goodbye", Replace:=wdReplaceAll

VBA Word Text formatting

One of the first things you would want to do is probably text formatting in Word VBA.

Let’s start by adding some text to our document:

'Select the beginning of the document
ActiveDocument.Range(0).Select
'Type "Hello World!"
Selection.TypeText Text:="Hello World!"

Bold & Italic

To change the font weight to bold see below:

'Select the word "Hello"
ActiveDocument.Range(0, 5).Select

'Toggle the bold property
Selection.Font.Bold = wdToggle

To change the text decoration to italic see below:

'Select the word "World"
ActiveDocument.Range(0, 5).Select
'Toggle the bold property
Selection.Font.Bold = wdToggle

Below the final result of the code above:
Word VBA Tutorial: Bold and Italic

Font size and name

Using the “Hello World!” example above we can similarly change the text font name and font size as shown below:

'Change font size
Selection.Font.Size = 20 'Size: 20
Selection.Font.Grow 'Size: 22
Selection.Font.Shrink 'Size: 20
'Change font name to "Aharoni"
Selection.Font.Name = "Aharoni"

VBA Word Tables

When editing Word files you might want to leverage tables as it is much easier to navigate around them in an automated way. My approach is to insert/modify tables in Word without and borders (invisible). This way you can guarantee a consistent and easy to navigate structure in Word. Let’s go through some of the basic functions around tables.

Add a table

Let’s add a table to the beginning of the Word document:

 Dim begin As Range
 Set startMark = ActiveDocument.Range(0, 0)
 'range as Range, NumRows as Long, NumColumns as Long
 Call ActiveDocument.Tables.Add(startMark, 3, 6) 'add to beginning of doc, 3 rows, 6 cols

Edit cell text

'Modify cell (1,3) to "Hello World!"
With ActiveDocument.Tables(1)
        .Cell(1, 3).Range.Text = "Hello World!"
End With

Working on rows and columns

With ActiveDocument.Tables(1)
        ' Modify height of row 1
        .Rows(1).Height = CentimetersToPoints(0.65)
        ' Modify width of column 1
        .Columns(1).Width = CentimetersToPoints(2.54)
        'Merge cell (1,3) with cell (1,4) - cells must be next to each other
        .Cell(1, 3).Merge .Cell(1, 4)
End With

Formatting borders

'Modify row 1 border, single, black and 100pt
 With ActiveDocument.Tables(1).Rows(3).Borders(wdBorderBottom)
        .LineStyle = wdLineStyleSingle
        .LineWidth = wdLineWidth100pt
        .Color = wdColorBlack
End With

In progress…

Использование Word в приложениях на Visual Basic 6 открывает широчайшие возможности для создания профессионально оформленных документов (например отчетов). Это часто необходимо при работе в фирме или на предприятии для обеспечения документооборота. Основным преимуществом использования Wordа в этом случае является то, что практически на всех компьютерах, используемых в фирмах и на предприятиях установлены Windows и пакет Microsoft Office. Поэтому подготовленные документы Word не требуют каких-либо дополнительных усилий для их просмотра, печати и редактирования. Единственное что нужно помнить, это то что работа через автоматизацию OLE (связывание и внедрение объектов) на деле оказывается довольно медленной технологией, хотя и очень полезной.

Чтобы использовать объекты Word в Visual Basic , необходимо инсталлировать сам Word. После этого вы получаете в своё распоряжение библиотеку Microsoft Word Object Library, которую нужно подключить к текущему проекту через диалоговое окно «Разработать»>>»Ссылки» (References) и указать Microsoft Word 9.0 Object Library (для Word 2000).

Два самых важных объекта Word это Word.Application и Word.Document. Они обеспечивают доступ к экземпляру приложения и документам Word.

Поэтому в раздел Generals «Общее» формы введите следующий код для объявления объектных переменных приложения Word и документа Word.

Dim WordApp As Word.Application '  экземпляр приложения
Dim DocWord As Word.Document'  экземпляр документа

Чтобы создать новый экземпляр Word, введите такой код кнопки;

Private Sub Комманда1_Click()

'создаём  новый экземпляр Word-a
Set WordApp = New Word.Application

'определяем видимость Word-a по True - видимый,
'по False - не видимый (работает только ядро)
WordApp.Visible = True

'создаём новый документ в Word-e
Set DocWord = WordApp.Documents.Add

'// если нужно открыть имеющийся документ, то пишем такой код
'Set DocWord = WordApp.Documents.Open("C:DDD.doc")

'активируем его
DocWord.Activate

End Sub

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

(вообще-то Word использует для всех размеров своих элементов пункты, поэтому для использования других единиц измерения, необходимо использовать встроенные функции форматирования.)

Например:

  • CentimetersToPoints(Х.ХХ) — переводит сантиметры в пункты.
  • MillimetersToPoints(X.XX) — переводит миллиметры в пункты
Private Sub Комманда2_Click()

'отступ слева "2,0 сантиметра"
DocWord.Application.Selection.PageSetup.LeftMargin = CentimetersToPoints(2)

'отступ справа "1,5 сантиметра"
DocWord.Application.Selection.PageSetup.RightMargin = CentimetersToPoints(1.5)

'отступ сверху "3,5 сантиметра"
DocWord.Application.Selection.PageSetup.TopMargin = CentimetersToPoints(3.5)

'отступ снизу "4,45 сантиметра"
DocWord.Application.Selection.PageSetup.BottomMargin = CentimetersToPoints(4.45)

End Sub

Небольшое отступление.

Для того чтобы в своём приложении не писать постоянно одно и тоже имя объекта, можно использовать оператор With.

Например код находящейся выше можно переписать так:

With DocWord.Application.Selection.PageSetup
.LeftMargin = CentimetersToPoints(2)
.RightMargin = CentimetersToPoints(1.5)
.TopMargin = CentimetersToPoints(3.5)
.BottomMargin = CentimetersToPoints(4.45)
End With

Если вам необходимо создать документ Word с нестандартным размером листа, то используйте данный код:

With DocWord.Application.Selection.PageSetup
.PageWidth = CentimetersToPoints(20)    'ширина листа (20 см)
.PageHeight = CentimetersToPoints(25)   'высота листа (25 см)
End With

Данный код меняет ориентацию страницы (практически меняет местами значения ширины и высоты листа):

 
DocWord.Application.Selection.PageSetup.Orientation = wdOrientLandscape
  • wdOrientLandscape — альбомная ориентация ( число 1)
  • wdOrientPortrait — книжная ориентация ( число 0)

Для сохранения документа под новым именем и в определенное место
используйте данный код код:

'сохраняем документ как
DocWord.SaveAs "c:DDD.doc"

После такого сохранения вы можете про ходу работы с документом сохранять его.

'сохраняем документ
DocWord.Save

Или проверить, были ли сохранены внесенные изменения свойством Saved и если изменения не были сохранены — сохранить их;

If DocWord.Saved=False Then DocWord.Save

Завершив работу с документом, вы можете закрыть сам документ методом Close и сам Word методом Quit.

'закрываем документ (без запроса на сохранение)
DocWord.Close True

'закрываем Word (без запроса на сохранение)
WordApp.Quit True

'уничтожаем обьект - документ
Set DocWord = Nothing

'уничтожаем обьект - Word
Set WordApp = Nothing

Если в методах Close и Quit не использовать необязательный параметр True то Word запросит согласие пользователя (если документ не был перед этим сохранён) на закрытие документа.

Если вам необходимо оставить Word открытым, просто не используйте методы Close и Quit.

Если вам необходимо поставить пароль на документ, то используйте код:

DocWord.Protect wdAllowOnlyComments, , "123456789"

Пример программы можно скачать здесь.

Понравилась статья? Поделить с друзьями:
  • Visual basic userform excel
  • Visual basic excel комментарии
  • Visual basic use in excel
  • Visual basic excel если не открыт файл то открыть
  • Visual basic excel диапазон