Vba создание документов word

Создание нового документа 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.

Using Excel VBA to create Microsoft Word documents

In these examples, we generate Microsoft Word Documents with various formatting features using
the Microsoft Excel VBA scripting language. These techniques can have many useful applications.
For instance if you have a list of data like a price or product list in Excel that you want to present
in a formatted Word Document, these techniques can prove useful.

In these examples, we assume the reader has at least basic knowledge of VBA, so we will not
go over basics of creating and running scripts. This code has been tested on Microsoft Word and Excel
2007. Some changes may be required for other versions of Word and Excel.

Writing to Word
Inserting a Table of Contents
Inserting Tabs
Inserting Tables
Inserting Bullet List
more on Inserting Tables
Multiple Features

Function that demonstrates VBA writing to a Microsoft Word document

The following code illustrates the use of VBA Word.Application object and related properties.
In this example, we create a new Word Document add some text.

    'In Tools > References, add reference to "Microsoft Word XX.X Object Library" before running.
	
    'Early Binding
    Dim wdApp As Word.Application
    Set wdApp = New Word.Application
    
    'Alternatively, we can use Late Binding
    'Dim wdApp As Object
    'Set wdApp = CreateObject("word.Application")
        
    With wdApp
        .Visible = True
        .Activate
        .Documents.Add
        
        With .Selection
            .ParagraphFormat.Alignment = wdAlignParagraphCenter
            .Font.Bold = True
            .Font.Name = "arial"
            .Font.Size = 14
            .TypeText ("My Heading")
            .TypeParagraph            
        End With
    End With 

Some VBA Vocabulary

ParagraphFormat
Represents all the formatting for a paragraph.

output in MS Word:

Inserting a Table of Contents into Word Document using Excel VBA

In this example, we generate a Table of Contents into a Word Document using Excel VBA

Sub sAddTableOfContents()
    
    Dim wdApp As Word.Application
    Set wdApp = New Word.Application
	
    'Alternatively, we can use Late Binding
    'Dim wdApp As Object
    'Set wdApp = CreateObject("word.Application")
    
    Dim wdDoc As Word.Document
    Set wdDoc = wdApp.Documents.Add
    
    ' Note we define a Word.range, as the default range wouled be an Excel range!
    Dim myWordRange As Word.range
    Dim Counter As Integer
    
    wdApp.Visible = True
    wdApp.Activate
    
    'Insert Some Headers
    With wdApp
        For Counter = 1 To 5
            .Selection.TypeParagraph
            .Selection.Style = "Heading 1"
            .Selection.TypeText "A Heading Level 1"
            .Selection.TypeParagraph
            .Selection.TypeText "Some details"
        Next
    End With

    ' We want to put table of contents at the top of the page
	Set myWordRange = wdApp.ActiveDocument.range(0, 0)
    
    wdApp.ActiveDocument.TablesOfContents.Add _
     range:=myWordRange, _
     UseFields:=False, _
     UseHeadingStyles:=True, _
     LowerHeadingLevel:=3, _
     UpperHeadingLevel:=1

End Sub

Some VBA Vocabulary

ActiveDocument.TablesOfContents.Add
The TablesOfContents property to return the TablesOfContents collection.
Use the Add method to add a table of contents to a document.

Some TablesOfContents Parameters

Range The range where you want the table of contents to appear. The table of contents replaces the range, if the range isn’t collapsed.

UseHeadingStyles True to use built-in heading styles to create the table of contents. The default value is True.

UpperHeadingLevel The starting heading level for the table of contents. Corresponds to the starting value used with the o switch for a Table of Contents (TOC) field. The default value is 1.

LowerHeadingLevel The ending heading level for the table of contents. Corresponds to the ending value used with the o switch for a Table of Contents (TOC) field. The default value is 9.

output Word Table in MS Word:

Write Microsoft Word Tabs

A function that writes tabbed content to a Microsoft Word Document. Note in each iteration, we change the
value of the leader character (characters that are inserted in the otherwise blank area created by the tab).

Public Sub sWriteMicrosoftTabs()

    'In Tools > References, add reference to "Microsoft Word XX.X Object Library" before running.
    
    'Early Binding
    Dim wdApp As Word.Application
    Set wdApp = New Word.Application
    
    'Alternatively, we can use Late Binding
    'Dim wdApp As Object
    'Set wdApp = CreateObject("word.Application")
        
    With wdApp
        .Visible = True
        .Activate
        .Documents.Add
    
        For Counter = 1 To 3
            .Selection.TypeText Text:=Counter & " - Tab 1 "
            
            ' position to 2.5 inches
            .Selection.Paragraphs.TabStops.Add Position:=Application.InchesToPoints(2.5), _
                Leader:=Counter, Alignment:=wdAlignTabLeft
            
            .Selection.TypeText Text:=vbTab & " - Tab 2 "
            
            ' position to 5 inches
            .Selection.Paragraphs.TabStops.Add Position:=Application.InchesToPoints(5), _
                Leader:=Counter, Alignment:=wdAlignTabLeft
            
            .Selection.TypeText Text:=vbTab & " - Tab 3 "
                    
            .Selection.TypeParagraph
        Next Counter
        
    End With
End Sub

Some VBA Vocabulary

.TabStops.Add Use the TabStops property to return the TabStops collection. In the example above,
nprogram adds a tab stop positioned at 0, 2.5 and 5 inches.

output in MS Word:

Write Microsoft Word Tables

In this example, we generate a Microsoft Table using Excel VBA

Sub sWriteMSWordTable ()
 
    'In Tools > References, add reference to "Microsoft Word XX.X Object Library" before running.
    
    'Early Binding
    Dim wdApp As Word.Application
    Set wdApp = New Word.Application
    
    'Alternatively, we can use Late Binding
    'Dim wdApp As Object
    'Set wdApp = CreateObject("word.Application")
        
    With wdApp
        .Visible = True
        .Activate
        .Documents.Add
        
        With .Selection
        
            .Tables.Add _
                    Range:=wdApp.Selection.Range, _
                    NumRows:=1, NumColumns:=3, _
                    DefaultTableBehavior:=wdWord9TableBehavior, _
                    AutoFitBehavior:=wdAutoFitContent
            
            For counter = 1 To 12
                .TypeText Text:="Cell " & counter
                If counter <> 12 Then
                    .MoveRight Unit:=wdCell
                End If
            Next
        
        End With
        
    End With

End Sub

Some VBA vocabulary

Table.AddTable object that represents a new, blank table added to a document.

Table.Add properties

Range The range where you want the table to appear. The table replaces the range, if the range isn’t collapsed.

NumRows The number of rows you want to include in the table.

NumColumns The number of columns you want to include in the table.

DefaultTableBehavior Sets a value that specifies whether Microsoft Word automatically resizes cells in tables to fit the cells� contents (AutoFit). Can be either of the following constants: wdWord8TableBehavior (AutoFit disabled) or wdWord9TableBehavior (AutoFit enabled). The default constant is wdWord8TableBehavior.

AutoFitBehavior Sets the AutoFit rules for how Word sizes tables. Can be one of the WdAutoFitBehavior constants.

output in MS Word:

Write Microsoft Word bullet list

In this example, we write with bullet list and outline numbers with Excel VBA

    'In Tools > References, add reference to "Microsoft Word XX.X Object Library" before running.
    
    'Early Binding
    Dim wdApp As Word.Application
    Set wdApp = New Word.Application
    
    'Alternatively, we can use Late Binding
    'Dim wdApp As Object
    'Set wdApp = CreateObject("word.Application")
    
    With wdApp
        .Visible = True
        .Activate
        .Documents.Add
        ' turn on bullets
        .ListGalleries(wdBulletGallery).ListTemplates(1).Name = ""
        .Selection.Range.ListFormat.ApplyListTemplate ListTemplate:=.ListGalleries(wdBulletGallery).ListTemplates(1), _
            continuepreviouslist:=False, applyto:=wdListApplyToWholeList, defaultlistbehavior:=wdWord9ListBehavior
        
        With .Selection
            .ParagraphFormat.Alignment = wdAlignParagraphLeft
            .Font.Bold = False
            .Font.Name = "Century Gothic"
            .Font.Size = 12
            .TypeText ("some details")
            .TypeParagraph
            .TypeText ("some details")
            .TypeParagraph
        End With
        
        ' turn off bullets
        .Selection.Range.ListFormat.RemoveNumbers wdBulletGallery
        
        With .Selection
            .ParagraphFormat.Alignment = wdAlignParagraphLeft
            .TypeText ("some details")
            .TypeParagraph
            .TypeText ("some details")
            .TypeParagraph
            
        End With
        
        ' turn on outline numbers
        .ListGalleries(wdOutlineNumberGallery).ListTemplates(1).Name = ""
        .Selection.Range.ListFormat.ApplyListTemplate ListTemplate:=.ListGalleries(wdOutlineNumberGallery).ListTemplates(1), _
            continuepreviouslist:=False, applyto:=wdListApplyToWholeList, defaultlistbehavior:=wdWord9ListBehavior
        
        With .Selection
            .ParagraphFormat.Alignment = wdAlignParagraphLeft
            .TypeText ("some details")
            .TypeParagraph
            .TypeText ("some details")
            
        End With
        
    End With

output in MS Word:

Another example of Writing Tables to Microsoft Word

In this example we will create a word document with 20 paragraphs. Each paragraph will have a header with a header style element

    
   'In Tools > References, add reference to "Microsoft Word XX.X Object Library" before running.
    Dim wdApp As Word.Application
    Dim wdDoc As Word.Document

    Set wdApp = New Word.Application
    wdApp.Visible = True
    
    
    Dim x As Integer
    Dim y As Integer
    
    wdApp.Visible = True
    wdApp.Activate
    wdApp.Documents.Add
            
    wdApp.ActiveDocument.Tables.Add Range:=wdApp.Selection.Range, NumRows:=2, NumColumns:= _
        2, DefaultTableBehavior:=wdWord9TableBehavior, AutoFitBehavior:= _
        wdAutoFitFixed
                
    With wdApp.Selection.Tables(1)
        If .Style <> "Table Grid" Then
            .Style = "Table Grid"
        End If
        .ApplyStyleHeadingRows = True
        .ApplyStyleLastRow = False
        .ApplyStyleFirstColumn = True
        .ApplyStyleLastColumn = False
        .ApplyStyleRowBands = True
        .ApplyStyleColumnBands = False
    End With
            
    With wdApp.Selection
        
        For x = 1 To 2
            ' set style name
            .Style = "Heading 1"
            .TypeText "Subject" & x
            .TypeParagraph
            .Style = "No Spacing"
            For y = 1 To 20
                .TypeText "paragraph text "
            Next y
            .TypeParagraph
        Next x
    
        ' new paragraph
        .TypeParagraph
        
        ' toggle bold on
        .Font.Bold = wdToggle
        .TypeText Text:="show some text in bold"
        .TypeParagraph
        
        'toggle bold off
        .Font.Bold = wdToggle
        .TypeText "show some text in regular front weight"
        .TypeParagraph
        
        
    End With
        
    

Some VBA vocabulary

TypeText

Inserts specified text at the beginning of the current selection. The selection is turned into an insertion point at the end of the inserted text.
If Options.ReplaceSelection = True then the original selection will be replaced. This behaves exactly the same as typing some text at the keyboard.

TypeParagraph

Insert a new blank paragraph. The selection is turned into an insertion point after the inserted paragraph mark. If Options.ReplaceSelection = True then the original selection will be replaced. This behaves exactly the same as pressing the Enter key.

output in MS Word:

Generating a Word table with VBA
	'In Tools > References, add reference to "Microsoft Word XX.X Object Library" before running.

	Dim wdApp As Word.Application
	Dim wdDoc As Word.Document
	Dim r As Integer

	Set wdApp = CreateObject("Word.Application")
	wdApp.Visible = True

	Set wdDoc = wdApp.Documents.Add
	wdApp.Activate

	Dim wdTbl As Word.Table
	Set wdTbl = wdDoc.Tables.Add(Range:=wdDoc.Range, NumRows:=5, NumColumns:=1)

	With wdTbl

		.Borders(wdBorderTop).LineStyle = wdLineStyleSingle
		.Borders(wdBorderLeft).LineStyle = wdLineStyleSingle
		.Borders(wdBorderBottom).LineStyle = wdLineStyleSingle
		.Borders(wdBorderRight).LineStyle = wdLineStyleSingle
		.Borders(wdBorderHorizontal).LineStyle = wdLineStyleSingle
		.Borders(wdBorderVertical).LineStyle = wdLineStyleSingle
		
		For r = 1 To 5
			.Cell(r, 1).Range.Text = ActiveSheet.Cells(r, 1).Value
		Next r
	End With

	

output in MS Word:

Option Explicit
Dim wdApp As Word.Application
 
Sub extractToWord()

   'In Tools > References, add reference to "Microsoft Word 12 Object Library" before running.
   
    Dim lastCell
    Dim rng As Range
    Dim row As Range
    Dim cell As Range
    Dim arrayOfColumns
    arrayOfColumns = Array("", "", "", "", "", "", "", "", "", "", "", "", "", "", "")
    Dim thisRow As Range
    Dim thisCell As Range
    Dim myStyle As String
    
    ' get last cell in column B
    lastCell = getLastCell()
    
    Set rng = Range("B2:H" & lastCell)
    
    'iterate through rows
    For Each thisRow In rng.Rows
            
        'iterate through cells in row row
        For Each thisCell In thisRow.Cells

            If thisCell.Value = arrayOfColumns(thisCell.Column) Or thisCell.Value = "" Then
            ' do nothing
                ''frWriteLine thisCell.Value, "Normal"
                ''frWriteLine arrayOfColumns(thisCell.Column), "Normal"
                  If thisCell.Value = arrayOfColumns(thisCell.Column) Or thisCell.Value = "" Then
                  End If
                  
            Else
                myStyle = "Normal"
                Select Case thisCell.Column
                    Case 2
                        myStyle = "Heading 1"
                    Case 3
                        myStyle = "Heading 2"
                    Case 4
                        myStyle = "Heading 3"
                    Case Is > 5
                        myStyle = "Normal"
                    
                End Select
                    
                frWriteLine thisCell.Value, myStyle
            End If
        
        arrayOfColumns(thisCell.Column) = thisCell.Value
    
      Next thisCell
    Next thisRow
    
End Sub

Public Function getLastCell() As Integer

    Dim lastRowNumber As Long
    Dim lastRowString As String
    Dim lastRowAddress As String
         
    With ActiveSheet
        getLastCell = .Cells(.Rows.Count, 2).End(xlUp).row
    End With
    
End Function

Public Function frWriteLine(someData As Variant, myStyle As String)
    
    If wdApp Is Nothing Then
        
        Set wdApp = New Word.Application
        With wdApp
            .Visible = True
            .Activate
            .Documents.Add
        End With
            
    End If
    
    With wdApp
        
        With .Selection
            .ParagraphFormat.Alignment = wdAlignParagraphCenter
            .Style = myStyle
            .TypeText (someData)
            .TypeParagraph
        End With
    End With
    
End Function

output in MS Word:

Содержание

  1. Как автоматизировать Microsoft Word с помощью Visual Basic для создания нового документа
  2. Аннотация
  3. Пример кода
  4. Использование шаблона
  5. Ссылки
  6. Working with Document Objects
  7. Creating a new document
  8. Opening a document
  9. Saving an existing document
  10. Saving a new document
  11. Closing documents
  12. Activating a document
  13. Determining if a document is open
  14. Referring to the active document
  15. Support and feedback
  16. Работа с объектами документа
  17. Создание нового документа
  18. Открытие документа
  19. Сохранение существующего документа
  20. Сохранение нового документа
  21. Закрытие документов
  22. Активация документа
  23. Определение того, открыт ли документ
  24. Ссылка на активный документ
  25. Поддержка и обратная связь
  26. Vba excel как создать документ word
  27. VBA Excel. Управление приложением Word
  28. Создание объекта Word.Application
  29. Раннее связывание приложения Word

Как автоматизировать Microsoft Word с помощью Visual Basic для создания нового документа

Аннотация

В этой пошаговой статье описывается создание нового документа в Word с помощью службы автоматизации из Visual Basic.

Пример кода

В примере кода в этой статье показано, как сделать следующее:

  • Вставка абзацев с текстом и форматированием.
  • Просмотр и изменение различных диапазонов в документе.
  • Вставка таблиц, форматирование таблиц и заполнение таблиц данными.
  • Добавление диаграммы.

Чтобы создать документ Word с помощью службы автоматизации из Visual Basic, выполните следующие действия.

В Visual Basic создайте проект EXE уровня «Стандартный». Form1 создается по умолчанию.

В меню «Проект » щелкните «Ссылки«, выберите один из следующих параметров и нажмите кнопку » ОК»:

  • Для Office Word 2007 щелкните библиотеку объектов Microsoft Word 12.0.
  • В Word 2003 щелкните библиотеку объектов Microsoft Word 11.0.
  • В Word 2002 щелкните библиотеку объектов Microsoft Word 10.0.
  • Для Word 2000 щелкните библиотеку объектов Microsoft Word 9.0.

Добавьте элемент управления CommandButton в Form1.

Добавьте следующий код в событие Click для Command1:

Нажмите клавишу F5, чтобы запустить программу, а затем нажмите кнопку Command1.

После завершения кода изучите созданный документ. Документ содержит две страницы форматированных абзацев, таблиц и диаграмм.

Использование шаблона

Если вы используете службу автоматизации для создания документов в общем формате, вы можете начать процесс с нового документа, основанного на предварительно сформированных шаблонах. Использование шаблона с клиентом word Automation имеет два существенных преимущества по сравнению с созданием документа из ничего:

  • Вы можете иметь более полный контроль над форматированием и размещением объектов в документах.
  • Вы можете создавать документы с меньшим объемом кода.

С помощью шаблона можно точно настроить размещение таблиц, абзацев и других объектов в документе, а также включить форматирование для этих объектов. С помощью службы автоматизации можно создать новый документ на основе шаблона с помощью следующего кода:

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

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

Ссылки

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

285332 Как автоматизировать Word 2002 с помощью Visual Basic для создания слияния

(c) Microsoft Corporation 2001, все права зарезервированы. Участие: Лори Б. Тертер (Lori B. Turner), корпорация Майкрософт.

Источник

Working with Document Objects

In Visual Basic, the methods for modifying files are methods of the Document object or the Documents collection. This topic includes Visual Basic examples related to the tasks identified in the following sections.

Creating a new document

The Documents collection includes all of the open documents. To create a new document, use the Add method to add a Document object to the Documents collection. The following instruction creates a document.

A better way to create a document is to assign the return value to an object variable. The Add method returns a Document object that refers to the new document. In the following example, the Document object returned by the Add method is assigned to an object variable. Then, several properties and methods of the Document object are set. You can easily control the new document using an object variable.

Opening a document

To open an existing document, use the Open method with the Documents collection. The following instruction opens a document named Sample.doc located in the MyFolder folder.

Saving an existing document

To save a single document, use the Save method with the Document object. The following instruction saves the document named Sales.doc.

You can save all open documents by applying the Save method to the Documents collection. The following instruction saves all open documents.

Saving a new document

To save a single document, use the SaveAs2 method with a Document object. The following instruction saves the active document as «Temp.doc» in the current folder.

The FileName argument can include only the file name or the complete path (for example, «C:DocumentsTemporary File.doc»).

Closing documents

To close a single document, use the Close method with a Document object. The following instruction closes and saves the document named Sales.doc.

You can close all open documents by applying the Close method of the Documents collection. The following instruction closes all documents without saving changes.

The following example prompts the user to save each document before the document is closed.

Activating a document

To change the active document, use the Activate method with a Document object. The following instruction activates the open document named Sales.doc.

Determining if a document is open

To determine if a document is open, you can enumerate the Documents collection by using a For Each. Next statement. The following example activates the document named Sample.doc if the document is open, or opens Sample.doc if it is not currently open.

Referring to the active document

Instead of referring to a document by name or by index number—for example, Documents(«Sales.doc») —the ActiveDocument property returns a Document object that refers to the active document (the document with the focus). The following example displays the name of the active document, or if there are no documents open, it displays a message.

Support and feedback

Have questions or feedback about Office VBA or this documentation? Please see Office VBA support and feedback for guidance about the ways you can receive support and provide feedback.

Источник

Работа с объектами документа

В Visual Basic методы изменения файлов являются методами объекта Document или коллекции Documents . В этом разделе приведены примеры Visual Basic, связанные с задачами, определенными в следующих разделах.

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

Коллекция Documents включает все открытые документы. Чтобы создать документ, используйте метод Add , чтобы добавить объект Document в коллекцию Documents . Следующая инструкция создает документ.

Лучший способ создания документа — назначить возвращаемое значение переменной объекта. Метод Add возвращает объект Document , который ссылается на новый документ. В следующем примере объект Document , возвращенный методом Add , назначается переменной объекта . Затем задаются несколько свойств и методов объекта Document . Вы можете легко управлять новым документом с помощью объектной переменной.

Открытие документа

Чтобы открыть существующий документ, используйте метод Open с коллекцией Documents . Следующая инструкция открывает документ с именем Sample.doc, расположенный в папке MyFolder.

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

Чтобы сохранить один документ, используйте метод Save с объектом Document . Следующая инструкция сохраняет документ с именем Sales.doc.

Вы можете сохранить все открытые документы, применив метод Save к коллекции Documents . Следующая инструкция сохраняет все открытые документы.

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

Чтобы сохранить один документ, используйте метод SaveAs2 с объектом Document . Следующая инструкция сохраняет активный документ как «Temp.doc» в текущей папке.

Аргумент FileName может включать только имя файла или полный путь (например, «C:DocumentsTemporary File.doc»).

Закрытие документов

Чтобы закрыть один документ, используйте метод Close с объектом Document . Следующая инструкция закрывает и сохраняет документ с именем Sales.doc.

Вы можете закрыть все открытые документы, применив метод Close коллекции Documents . Следующая инструкция закрывает все документы без сохранения изменений.

В следующем примере пользователю предлагается сохранить каждый документ перед закрытием документа.

Активация документа

Чтобы изменить активный документ, используйте метод Activate с объектом Document . Следующая инструкция активирует открытый документ с именем Sales.doc.

Определение того, открыт ли документ

Чтобы определить, открыт ли документ, можно перечислить коллекцию Documents с помощью параметра For Each. Следующая инструкция. В следующем примере документ с именем Sample.doc активируется, если документ открыт, или открывается Sample.doc, если он в настоящее время не открыт.

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

Вместо ссылки на документ по имени или по номеру индекса, например, Documents(«Sales.doc») свойство ActiveDocument возвращает объект Document , ссылающийся на активный документ (документ с фокусом). В следующем примере отображается имя активного документа или, если документы не открыты, отображается сообщение.

Поддержка и обратная связь

Есть вопросы или отзывы, касающиеся Office VBA или этой статьи? Руководство по другим способам получения поддержки и отправки отзывов см. в статье Поддержка Office VBA и обратная связь.

Источник

Vba excel как создать документ word

In these examples, we generate Microsoft Word Documents with various formatting features using the Microsoft Excel VBA scripting language. These techniques can have many useful applications. For instance if you have a list of data like a price or product list in Excel that you want to present in a formatted Word Document, these techniques can prove useful.

In these examples, we assume the reader has at least basic knowledge of VBA, so we will not go over basics of creating and running scripts. This code has been tested on Microsoft Word and Excel 2007. Some changes may be required for other versions of Word and Excel.

Function that demonstrates VBA writing to a Microsoft Word document

The following code illustrates the use of VBA Word.Application object and related properties. In this example, we create a new Word Document add some text.

Some VBA Vocabulary

ParagraphFormat Represents all the formatting for a paragraph.

output in MS Word:

Inserting a Table of Contents into Word Document using Excel VBA

In this example, we generate a Table of Contents into a Word Document using Excel VBA

Some VBA Vocabulary

ActiveDocument.TablesOfContents.Add The TablesOfContents property to return the TablesOfContents collection. Use the Add method to add a table of contents to a document.

Some TablesOfContents Parameters

Range The range where you want the table of contents to appear. The table of contents replaces the range, if the range isn’t collapsed.

UseHeadingStyles True to use built-in heading styles to create the table of contents. The default value is True.

UpperHeadingLevel The starting heading level for the table of contents. Corresponds to the starting value used with the o switch for a Table of Contents (TOC) field. The default value is 1.

LowerHeadingLevel The ending heading level for the table of contents. Corresponds to the ending value used with the o switch for a Table of Contents (TOC) field. The default value is 9.

output Word Table in MS Word:

Write Microsoft Word Tabs

A function that writes tabbed content to a Microsoft Word Document. Note in each iteration, we change the value of the leader character (characters that are inserted in the otherwise blank area created by the tab).

Some VBA Vocabulary

.TabStops.Add Use the TabStops property to return the TabStops collection. In the example above, nprogram adds a tab stop positioned at 0, 2.5 and 5 inches.

output in MS Word:

Write Microsoft Word Tables

In this example, we generate a Microsoft Table using Excel VBA

Some VBA vocabulary

Table.Add Table object that represents a new, blank table added to a document.

Range The range where you want the table to appear. The table replaces the range, if the range isn’t collapsed.

NumRows The number of rows you want to include in the table.

NumColumns The number of columns you want to include in the table.

DefaultTableBehavior Sets a value that specifies whether Microsoft Word automatically resizes cells in tables to fit the cells� contents (AutoFit). Can be either of the following constants: wdWord8TableBehavior (AutoFit disabled) or wdWord9TableBehavior (AutoFit enabled). The default constant is wdWord8TableBehavior.

AutoFitBehavior Sets the AutoFit rules for how Word sizes tables. Can be one of the WdAutoFitBehavior constants.

output in MS Word:

Write Microsoft Word bullet list

In this example, we write with bullet list and outline numbers with Excel VBA

Источник

VBA Excel. Управление приложением Word

Создание нового экземпляра приложения Word из кода VBA Excel или подключение к открытому для работы с документами. Функции CreateObject и GetObject.

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

Создание объекта Word.Application

Экземпляр приложения Word необходим для того, чтобы с его помощью создавать новые документы или открывать существующие для редактирования из кода VBA Excel.

Создать новый экземпляр объекта Word.Application можно при помощи раннего или позднего связывания, используя при позднем связывании функцию CreateObject. Подключиться к открытому экземпляру приложения Word можно только при помощи позднего связывания, используя функцию GetObject.

Раннее связывание приложения Word

Создание нового экземпляра Word.Application и присвоение ссылки на него переменной myWord:

Для раннего связывания переменной с объектом Word.Application необходимо подключить в редакторе VBA Excel ссылку на библиотеку Microsoft Word Object Library, если она не подключена. Подключается ссылка в окне «References VBAproject», перейти в которое можно через главное меню редактора: Tools–>References…

Раннее связывание позволяет при написании кода использовать лист подсказок для выбора и вставки свойств и методов привязанных объектов (Auto List Members). Если проект VBA Excel создается на заказ, то, после его завершения, раннее связывание следует заменить на позднее, так как на компьютере пользователя может не оказаться нужной библиотеки, и код работать не будет.

Источник

Использование 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"

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

Содержание

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

Понравилась статья? Поделить с друзьями:
  • Vba снять пароль с книги excel
  • Vba снять выделение word
  • Vba скрыть пустые строки в excel
  • Vba скрипты для word
  • Vba скрипты для excel что это