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

Open Word Document

This Word VBA Macro will open a word document from the specified directory:

Sub OpenDoc()
    Dim strFile As String

    strFile = "c:UsersNenadDesktopTest PM.docm"    'change to path of your file
    If Dir(strFile) <> "" Then    'First we check if document exists at all at given location
        Documents.Open strFile
    End If
End Sub

Now you can interact with the newly opened document with the ActiveDocument Object. This code will add some text to the document.

ActiveDocument.Range(0, 0).Text = "Add Some Text"

Open Document to Variable

You can also open a Word document, immediately assigning it to a variable:

Sub OpenDoc()
    Dim strFile As String
    Dim oDoc as Document

    strFile = "c:UsersNenadDesktopTest PM.docm"    'change to path of your file
    If Dir(strFile) <> "" Then    'First we check if document exists at all at given location
        Set oDoc = Documents.Open strFile
    End If
End Sub

Allowing you to interact with the document via the variable oDoc.:

oDoc.Range(0, 0).Text = "Add Some Text"

Generally it’s best practice to open to a variable, giving you the ability to easily reference the document at any point.

Open Word Document From Excel

This VBA procedure will open a Word Document from another MS Office program (ex. Excel):

Sub OpenDocFromExcel()
    Dim wordapp
    Dim strFile As String


    strFile = "c:UsersNenadDesktopTest PM.docm"
    Set wordapp = CreateObject("word.Application")
    wordapp.Documents.Open strFile
    wordapp.Visible = True
End Sub

Word VBA, Open Document

Jun 07, 2015 in Dialogs

In this article I will explain how you can open a word document using VBA.


Opening Word Document:

If you are opening a word document from word you can use the code below:

Sub main()
Documents.Open ("D:TestFolderMain.docx")
End Sub

Where “D:TestFolderMain.docx” is the path where the word document is located.


Opening Word Document From Other Applications:

If you are opening a word document from another application, you would need to automate a word application first. This can be done using the code below:

Sub main()
Dim objWord As Object
'automate word application
Set objWord = CreateObject("Word.Application")
objWord.Visible = True
'open word document
objWord.documents.Open ("D:TestFolderMain.docx")
End Sub

For more information about automating word applications please see the article below:

  • VBA, Automating Word From Excel


Using Open File Dialogs

You could also ask the user to choose the path of the word document using an open file dialogs. I have covered this topic in detail in the article below. Although the article was written for VBA for Excel, the concept can also be used in VBA for Word:

  • Excel VBA, Open File Dialog

In the sample code below the user is asked to select the location of the word file from an open file dialog. After selecting the file, it is opened:

Sub main()
Dim intChoice As Integer
Dim strPath As String
Dim objWord As Object
Set objWord = CreateObject("Word.Application")
objWord.Visible = True

Application.FileDialog(msoFileDialogOpen).AllowMultiSelect = False
intChoice = Application.FileDialog(msoFileDialogOpen).Show
'if the user selects a file
If intChoice <> 0 Then
    'get the path selected
    strPath = Application.FileDialog( _
        msoFileDialogOpen).SelectedItems(1)
    'opens the document
    objWord.documents.Open (strPath)
End If
End Sub

 See also:

  • VBA, Automating Word From Excel
  • Word Automation VBA, Common Errors
  • Word VBA, Apply Macro to Multiple Files
  • Word VBA, Modify Header For Multiple Files
  • Word Automation VBA, Common Errors
  • VBA, Write Excel Values to Word Document

If you need assistance with your code, or you are looking for a VBA programmer to hire feel free to contact me. Also please visit my website  www.software-solutions-online.com

title keywords f1_keywords ms.prod api_name ms.assetid ms.date ms.localizationpriority

Documents.Open method (Word)

vbawd10.chm158072851

vbawd10.chm158072851

word

Word.Documents.Open

9e61e9d5-58d1-833a-5f93-b87299deb400

06/08/2017

medium

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

Document

Security

[!IMPORTANT]
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.

Sub OpenDoc() 
 Documents.Open FileName:="C:MyFilesMyDoc.doc", ReadOnly:=True 
End Sub

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

Sub OpenDoc2() 
 Dim fmt As Variant 
 fmt = Application.FileConverters("WordPerfect6x").OpenFormat 
 Documents.Open FileName:="C:MyFilesTest.wp", Format:=fmt 
End Sub

[!includeSupport and feedback]

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

Like this post? Please share to your friends:
  • Vba for search in excel
  • Vba opening excel file
  • Vba for save in excel
  • Vba open excel from word
  • Vba for microsoft excel 2010