Documents open excel vba

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

Every time I try to open a word document in VBA excel I get a pop up window in the background that asks me how to open it because it is tagged as read-only. I have looked at the properties of the file and it isn’t read-only however it is in revision control (tortoise-SVN).

Sub ReadSpec()
'References
'  Microsoft Word 14.0 Object library
'
Dim Paragraphe As Object

Dim WordApp As Word.Application
Set WordApp = CreateObject("Word.Application")

Dim WordDoc As Word.Document
Set WordDoc = WordApp.Documents.Open("Spec.docx")
WordApp.Visible = True

WordDoc.Close
WordApp.Quit


End Sub

David Zemens's user avatar

David Zemens

52.8k11 gold badges79 silver badges129 bronze badges

asked Jun 10, 2013 at 13:55

engineer Mike's user avatar

2

The file may be in use by another application which is why you’re being told it is read-only. This isn’t a problem unless you want to write to the file. If you’re only trying to read from it my suggestion is to add

Application.DisplayAlerts = False

to see if it gets rid of the prompt for you. Also note that it is generally good practice to do something more along the lines of

Sub YourMethod
    Dim PrevDispAlerts as Boolean

    PrevDispAlerts = Application.DisplayAlerts
    Application.DisplayAlerts = False

    'code that does something goes here

    Application.DisplayAlerts = PrevDispAlerts
End Sub

answered Jun 10, 2013 at 14:03

Ripster's user avatar

RipsterRipster

3,5252 gold badges19 silver badges28 bronze badges

0

I’m not familiar with SVN but you might try either:

.Open("Spec.docx", ReadOnly=False) 

or

.Open("Spec.docx", ConfirmConversions=False, ReadOnly=False)

These suppress two common dialogs and force the default behavior. If you needed to override you would have to either make that explicit in the above code (i.e., ReadOnly=True to force read only) or just allow the dialog to display, using your original code.

answered Jun 10, 2013 at 21:54

David Zemens's user avatar

David ZemensDavid Zemens

52.8k11 gold badges79 silver badges129 bronze badges

I suppose it depends on the version of Excel. Solutions often work for one version but not another.

http://smallbusiness.chron.com/open-word-document-excel-using-vba-40430.html

I found this code worked.

'Open an existing Word Document from Excel
Dim objWord As Object
Set objWord = CreateObject("Word.Application")
objWord.Visible = True
'Change the directory path and file name to the location
'of the document you want to open from Excel
objWord.Documents.Open "C:Documentsmyfile.doc"

answered Jul 20, 2013 at 13:06

user2602261's user avatar

hmmm not familiar with SVN but you might try

 .Open("Spec.docx", ReadOnly=False) or Open("Spec.docx", ConfirmConversions=False, ReadOnly=False)

answered Jun 10, 2013 at 21:43

engineer Mike's user avatar

engineer Mikeengineer Mike

772 gold badges2 silver badges7 bronze badges

1

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 "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")
        
    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

Содержание

  1. How to Open a Word Document from Excel and Copy Excel Data to the Word Document using VBA
  2. Tools you can use
  3. Create and Open a New Word Document using Macro
  4. Copy Excel Data into a Newly Created Word Document
  5. Documents.Open method (Word)
  6. Syntax
  7. Parameters
  8. Return value
  9. Security
  10. Example
  11. Support and feedback
  12. Объект Documents (Word)
  13. Замечания
  14. См. также
  15. Поддержка и обратная связь
  16. Метод Documents.Open (Word)
  17. Синтаксис
  18. Параметры
  19. Возвращаемое значение
  20. Безопасность
  21. Пример
  22. Поддержка и обратная связь

How to Open a Word Document from Excel and Copy Excel Data to the Word Document using VBA

Tools you can use

Create and Open a New Word Document using Macro

First, let’s create a new word document using a Macro. We can use the CreateObject() method in VBA to create a new instance of a Word document.

In the above example, I am just creating new instance of a Word document and making it visible, that is, it will open the word file (or document).

Now, we need to add a blank document to the word file. This is where you write your stuff, add table etc.

Activating the document, will set focus on the word file. You can skip the .Activate part, Excel will simply create a word file, and you can see the file in your task bar .

So, now you know how to create a new Word document from Excel using VBA. It’s a simple method. Let’s write the entire code in a procedure.

You can call the above procedure from a button click event, or execute the code when your workbook loads .

Copy Excel Data into a Newly Created Word Document

Now the real code. Did you see the first image in this post? It shows what I am going to do here in this example.

I have range of data in Excel, a table with few columns and rows. I also have a button (an ActiveX control). I wish to create a new word file from my VBA macro and copy the Excel data in the Word file (or document).

I want the data in table format in my word document. Its a very interesting example. You should.

First, create a range of data in Excel. You and add or remove columns or rows from the range. Since, in the example, I am using the UsedRange property to extract data from the worksheet.

Источник

Documents.Open method (Word)

Opens the specified document and adds it to the Documents collection. Returns a Document object.

Syntax

expression.Open (FileName, ConfirmConversions, ReadOnly, AddToRecentFiles, PasswordDocument, PasswordTemplate, Revert, WritePasswordDocument, WritePasswordTemplate, Format, Encoding, Visible, OpenConflictDocument, OpenAndRepair, DocumentDirection, NoEncodingDialog)

expression Required. A variable that represents a Documents object.

Parameters

Name Required/Optional Data type Description
FileName Required Variant The name of the document (paths are accepted).
ConfirmConversions Optional Variant True to display the Convert File dialog box if the file isn’t in Microsoft Word format.
ReadOnly Optional Variant True to open the document as read-only. This argument doesn’t override the read-only recommended setting on a saved document. For example, if a document has been saved with read-only recommended turned on, setting the ReadOnly argument to False will not cause the file to be opened as read/write.
AddToRecentFiles Optional Variant True to add the file name to the list of recently used files at the bottom of the File menu.
PasswordDocument Optional Variant The password for opening the document.
PasswordTemplate Optional Variant The password for opening the template.
Revert Optional Variant Controls what happens if FileName is the name of an open document. True to discard any unsaved changes to the open document and reopen the file. False to activate the open document.
WritePasswordDocument Optional Variant The password for saving changes to the document.
WritePasswordTemplate Optional Variant The password for saving changes to the template.
Format Optional Variant The file converter to be used to open the document. Can be one of the WdOpenFormat constants. The default value is wdOpenFormatAuto. To specify an external file format, apply the OpenFormat property to a FileConverter object to determine the value to use with this argument.
Encoding Optional Variant The document encoding (code page or character set) to be used by Microsoft Word when you view the saved document. Can be any valid MsoEncoding constant. For the list of valid MsoEncoding constants, see the Object Browser in the Visual Basic Editor. The default value is the system code page.
Visible Optional Variant True if the document is opened in a visible window. The default value is True.
OpenConflictDocument Optional Variant Specifies whether to open the conflict file for a document with an offline conflict.
OpenAndRepair Optional Variant True to repair the document to prevent document corruption.
DocumentDirection Optional WdDocumentDirection Indicates the horizontal flow of text in a document. The default value is wdLeftToRight.
NoEncodingDialog Optional Variant True to skip displaying the Encoding dialog box that Word displays if the text encoding cannot be recognized. The default value is False.

Return value

Security

Avoid using hard-coded passwords in your applications. If a password is required in a procedure, request the password from the user, store it in a variable, and then use the variable in your code. For recommended best practices on how to do this, see Security notes for Office solution developers.

Example

This example opens MyDoc.doc as a read-only document.

This example opens Test.wp using the WordPerfect 6.x file converter.

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.

Источник

Объект Documents (Word)

Коллекция всех объектов Document , которые в настоящее время открыты в Word.

Замечания

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

Используйте метод Add , чтобы создать пустой документ и добавить его в коллекцию Documents . В следующем примере создается новый документ на основе шаблона Обычный.

Используйте метод Open , чтобы открыть файл. В следующем примере открывается документ с именем «Sales.doc».

Используйте Documents (Index), где Index — это имя документа или номер индекса для возврата одного объекта Document . Следующая инструкция закрывает документ с именем «Report.doc» без сохранения изменений.

Номер индекса представляет позицию документа в коллекции Documents . В следующем примере активируется первый документ в коллекции Documents .

В следующем примере перечисляется коллекция Documents , чтобы определить, открыт ли документ с именем «Report.doc». Если этот документ содержится в коллекции Документы , он активируется; В противном случае он открывается.

См. также

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

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

Источник

Метод Documents.Open (Word)

Открывает указанный документ и добавляет его в коллекцию Documents . Возвращает объект Document .

Синтаксис

expression. Открыть (FileName, ConfirmConversions, ReadOnly, AddToRecentFiles, PasswordDocument, PasswordTemplate, Revert, WritePasswordDocument, WritePasswordTemplate, Format, Encoding, Visible, OpenConflictDocument, OpenAndRepair, DocumentDirection, NoEncodingDialog)

выражение (обязательно). Переменная, представляющая объект Documents .

Параметры

Имя Обязательный или необязательный Тип данных Описание
FileName Обязательный Variant Имя документа (пути принимаются).
ConfirmConversions Необязательный Variant Значение true для отображения диалогового окна Преобразовать файл , если файл не имеет формат Microsoft Word.
ReadOnly Необязательно устанавливать. Variant Значение true , чтобы открыть документ только для чтения. Этот аргумент не переопределяет рекомендуемый параметр только для чтения для сохраненного документа. Например, если документ сохранен с включенным параметром «Только для чтения», установка аргумента ReadOnly значения False не приведет к открытию файла в режиме чтения и записи.
AddToRecentFiles Необязательный Variant Значение true , чтобы добавить имя файла в список недавно использовавшихся файлов в нижней части меню Файл .
PasswordDocument Необязательный Variant Пароль для открытия документа.
PasswordTemplate Необязательный Variant Пароль для открытия шаблона.
Вернуться Необязательный Variant Управляет тем, что происходит, если Имя_файла — это имя открытого документа. Значение true , чтобы отменить все несохраненные изменения в открытом документе и повторно открыть файл. Значение False для активации открытого документа.
WritePasswordDocument Необязательный Variant Пароль для сохранения изменений в документе.
WritePasswordTemplate Необязательный Variant Пароль для сохранения изменений в шаблоне.
Format Необязательный Variant Преобразователь файлов, используемый для открытия документа. Может быть одной из констант WdOpenFormat . Значение по умолчанию — wdOpenFormatAuto. Чтобы указать внешний формат файла, примените свойство OpenFormat к объекту FileConverter , чтобы определить значение, используемое с этим аргументом.
Encoding Необязательный Variant Кодировка документа (кодовая страница или набор символов), используемая Microsoft Word при просмотре сохраненного документа. Может быть любой допустимой константой MsoEncoding . Список допустимых констант MsoEncoding см. в обозревателе объектов в редакторе Visual Basic. Значение по умолчанию — системная кодовая страница.
Visible Необязательный Variant Значение true , если документ открыт в видимом окне. Значение по умолчанию — True.
OpenConflictDocument Необязательный Variant Указывает, следует ли открывать файл конфликта для документа с автономным конфликтом.
OpenAndRepair Необязательный Variant Значение true для восстановления документа, чтобы предотвратить повреждение документа.
DocumentDirection Необязательный WdDocumentDirection Указывает горизонтальный поток текста в документе. Значение по умолчанию — wdLeftToRight.
NoEncodingDialog Необязательный Variant Значение true , чтобы пропустить отображение диалогового окна Кодировка, которое отображается в Word, если кодировка текста не распознана. Значение по умолчанию — False.

Возвращаемое значение

Безопасность

Избегайте использования в приложениях жестко заданных паролей. Если в процедуре требуется пароль, запросите пароль у пользователя, сохраните его в переменной, а затем используйте эту переменную в коде. Рекомендации по этому способу см. в статье Заметки о безопасности для разработчиков решений Office.

Пример

В этом примере MyDoc.doc открывается как документ только для чтения.

В этом примере открывается Файл Test.wp с помощью преобразователя файлов WordPerfect 6.x.

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

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

Источник

This post will show you how to open a word document from Excel using VBA. This is a great technique for Excel developers building dashboards or reports when you want to open a specific word document containing additional notes.

Introduction

Excel VBA can help you automate the creation of Excel dashboards and reports but it can do almost anything you want, including opening up documents from other software sources like Microsoft Word.

A great example of why you might want to use Excel VBA to open up a Word document is when you are creating Excel dashboards that have additional commentary or notes contained in Word, or perhaps more detailed guidance to match your dashboard.

To begin with you need to be in the Excel VBA editor, this can be done either by selecting Developer > Visual Basic on the Excel ribbon or just press ALT and F11 (pressed together) to use a shortcut command.

Open Word with Excel VBA

With the Visual Basic Editor window now insert a new module by clicking Insert then Module from the drop down menu bar at the top of the window.

Open Word with Excel VBA

This enables a new code window where we can include the VBA code required to open a word document from Excel.

Open Word with Excel VBA

In the code window insert the following script, remember to change the INSERT FILE NAME section to the full path and document name of your word document. You must include the file type at the end so for word this will either be .doc or .docx depending on what version of word you use.

For example if your word document is stored in C:MyDocuments and called MyWordDocument then you would replace INSERT FILE NAME with “C:MyDocumentsMyWordDocument.docx”

Sub OpnWord()

Dim oAPP As Object

Set oAPP = CreateObject(Class:="Word.Application")

oAPP.Visible = True

oAPP.Documents.Open Filename:="INSERT FILE NAME"

End Sub

Next save the Excel file (remember to save as a Macro-Enabled file) and you now have a script that will open up the specified word document when it is run.

Understanding the VBA code

Each line of the VBA performs a specific task, understanding what each line does will help you to edit the VBA if needed.

  • Sub OpnWord()

This line starts and name the procedure, if you don’t like the name “OpnWord” you can change it.

  • Dim oAPP as Object

This tells Excel that the name “oAPP” will be an object when we define it.  It is common practice in VBA scripts to take longer pieces of code and shorten them to a smaller name, in this case oAPP is my way of shortening Office Application.

  • Set oAPP = CreateObject(Class:=”Word.Application”)

Now we have defined the object oAPP this line tells Excel what oAPP is.  oAPP refers to the line of script CreateObject(Class:=”Word.Application”) and that is telling Excel that oAPP is the application Microsoft Word.

  • oAPP.Visible = True

Once Excel knows that oAPP is the application Microsoft Word this line tells Excel to open Word and make it visible to the user.

  • oAPP.Documents.Open Filename:=”INSERT FILE NAME”

This line specifies the Microsoft Word filename to open, remember to change the INSERT FILE NAME section to include the full path, file name and document type of the Word file to open.

  • End Sub

This tells Excel the VBA script ends.

Practical uses for this script

When you have created the macro using the script above it can be assigned to buttons or other objects in your Excel dashboard, that way a word document of your choosing will automatically open for the user when they click on the button.

This code also acts as a base to take things further. Now that you can open a word document from Excel VBA it is possible to populate that Word document with charts, tables and data from Excel. This is a very useful technique to learn as it helps you automate management reports from an Excel dashboard. The possibilities are endless!

Keep Excelling,

Please check out the other posts on this site to learn even more amazing things you can do with Excel. For those of you who would love a good book covering all these techniques and more then I highly recommend VBA and Macros for Excel. You can check out a copy on Amazon by clicking the image below.

Понравилась статья? Поделить с друзьями:
  • Documents microsoft word download
  • Documents add word vba
  • Documentary about spoken word
  • Document write use these words and word
  • Document word search software