Dim wordapp as word application

 

postrelll

Пользователь

Сообщений: 7
Регистрация: 28.03.2016

#1

02.09.2016 12:23:58

Добрый день, столкнулся со следующей проблемой в 2016 офисе.

Есть макрос, выполняющий роль заполнялки документов по шаблону. Выполняется макрос из excel файлика, среди шаблонов есть Word документы, соответсвенно приходится в самом макросе оперировать с этими word объектами через Word.Application. Макрос корректно работал на версии офиса 2010 и младше. Сейчас установили 2016 офис и возникла проблема — при выполнении одной из строк кода возникает ошибка

Код
Run-Time Error 4605
Данная команда недоступна

Начальная инициализация

Код
Dim WordApp As Object

Set WordApp = CreateObject("Word.Application")
With WordApp
        .Visible = False
        .WindowState = wdWindowStateNormal
        .ScreenUpdating = False
End With

Проблемная функция

Код
Private Sub WordReplacement(word_selection As String, _
                            replacement_text As String, _
                            appobject As Object)
                             
    appobject .Application.Selection.Find.ClearFormatting
    appobject .Application.Selection.Find.Replacement.ClearFormatting

    With appobject.Application.Selection.Find
        .Text = word_selection
        .Replacement.Text = replacement_text
        appobject .Application.Selection.Find.Execute Replace:=wdReplaceAll
    End With

Проблемная строка на которой светится ошибка 4605

Код
 appobject .Application.Selection.Find.Execute Replace:=wdReplaceAll
End Sub

Буду рад любой помощи

 

The_Prist

Пользователь

Сообщений: 14181
Регистрация: 15.09.2012

Профессиональная разработка приложений для MS Office

А на этой строке нет ошибки?
.WindowState = wdWindowStateNormal
точно? Зачем Вам позднее связывание, если внутри кода напихали констант ворда?
Советую ознакомиться:

Как из Excel обратиться к другому приложению

проблема в том, что Excel ничего не знает о константах Word-а, в том числе и про эту: wdReplaceAll

Изменено: The_Prist02.09.2016 12:29:09

Даже самый простой вопрос можно превратить в огромную проблему. Достаточно не уметь формулировать вопросы…

 

postrelll

Пользователь

Сообщений: 7
Регистрация: 28.03.2016

#3

02.09.2016 12:43:05

The_Prist
Да, все верно, именно поэтому приходится в начале инициализировать экземпляр объекта Word.Application
.WindowState = wdWindowStateNormal — на эту строку не ругается
Инициализация объекта Word.Application идет в самом начале макроса. Если я убираю вот эту строку из кода

Код
appobject .Application.Selection.Find.Execute Replace:=wdReplaceAll

То макрос выполняется без ошибок. Шаблон с Word документом сохраняется с нужным мне именем. Однако нужных мне замен в этом шаблоне не производится.

ПОдключенные библиотеки

<#1><#2>

 

Hugo

Пользователь

Сообщений: 23249
Регистрация: 22.12.2012

#4

02.09.2016 12:48:58

Вместо констант пишите явно значение этих констант.

Код
Const wdReplaceAll = 2
    Member of Word.WdReplace

Изменено: Hugo02.09.2016 13:00:20

 

postrelll

Пользователь

Сообщений: 7
Регистрация: 28.03.2016

Проблема решена  — поменял формат шаблонов на .docx и переместил их с системного диска в документы пользователя.

 

The_Prist

Пользователь

Сообщений: 14181
Регистрация: 15.09.2012

Профессиональная разработка приложений для MS Office

#6

02.09.2016 13:51:39

Цитата
postrelll написал: Проблема решена

не хотите Вы прислушиваться и читать…Она обязательно может всплыть в другой раз. Т.к. библиотека Word 16 может не подхватиться на более ранних.
Сказать, почему макрос выполняется без ошибок? потому что все остальные переменные Word-а, возможно, тупо как 0 воспринимаются, т.к. директива Option Explicit не объявлена. И это тоже может повлечь свои ошибки.

Даже самый простой вопрос можно превратить в огромную проблему. Достаточно не уметь формулировать вопросы…

 

postrelll

Пользователь

Сообщений: 7
Регистрация: 28.03.2016

The_Prist
Да, я понимаю значение директивы Option Explicit.
Макрос выполняется корректно и результат так же корректен.

Проблема была в «безопасном режиме» шаблона, который открывался. В моем случае макрос открывал шаблон из указанного пути. В шаблоне в цикле делал замены в нужные места документов и затем сохранял шаблон под определенным именем. Ошибка изначально была связана с тем, что при открытии шаблона в безопасном режиме его невозможно редактировать, соответственно и делать замены в нём так же нельзя. А этот безопасный режим появился только в 2016 офисе (возможно и в 2013 он так же есть), поскольку в 2010 все открывалось нормально в обычном режиме. Стоит так же сказать, что шаблоны были в .doc формате для лучшей совместимости с более старыми офисами, поскольку макросом пользуются на самых разных ПК. Из-за этого и выползала ошибка.

Плюс я изначально все шаблоны загонял в отдельную папку на диске С.  Учитывая, что макрос сейчас запускается из-под WIn 10, проблему так же создавала встроенная защита системы, поскольку она любит подтверждать через UAC все процедуры перезаписи/удаления. Поэтому и перенес папку с шаблонами в документы пользователя.

Изменено: postrelll02.09.2016 17:05:03

 

Сергей Редькин

Пользователь

Сообщений: 1
Регистрация: 11.07.2021

#8

19.01.2022 08:58:23

У меня была похожая проблема со вставкой неформатированных значений из ячеек в размеченные закладками места в Word. Ошибки периодически вылазили на этой строке:

Код
.Application.Selection.PasteAndFormat (wdFormatPlainText)

Перенос файла шаблона в папку шаблонов по умолчанию не помог. Насколько понимаю проблемы возникают при вызове функций Word из VBA, запущенном в Excel, но до конца в причинах я так и не разобрался. Заменил Copy/Paste на вставку значения текстовой переменной. Самое интересное, что один Selection.Copy / Selection.PasteAndFormat (wdFormatPlainText) в самом конце макроса работает корректно, но как только вставляю в макрос несколько — вылазят ошибки.

Код
Sub CreateLetter()
Dim wdApp As Word.Application
Dim wdDoc As Word.Document
Dim SaveAsName As String

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

Set wdDoc = wdApp.Documents.Add(Template:="C:____.dotx", NewTemplate:=False, DocumentType:=0)

With wdDoc
       
    Text = Cells(6, 2).Text
    .Application.Selection.Goto wdGoToBookmark, , , "Должность"
    .Application.Selection.ParagraphFormat.Alignment = wdAlignParagraphCenter
    .Application.Selection.InsertAfter (Text)
       
    Text = Cells(6, 1).Text
    .Application.Selection.Goto wdGoToBookmark, , , "Организация"
    .Application.Selection.ParagraphFormat.Alignment = wdAlignParagraphCenter
    .Application.Selection.InsertAfter (Text)

    Text = Cells(6, 3).Text
    .Application.Selection.Goto wdGoToBookmark, , , "Кому"
    .Application.Selection.ParagraphFormat.Alignment = wdAlignParagraphCenter
    .Application.Selection.InsertAfter (Text)
    
    Text = Cells(6, 4).Text
    .Application.Selection.Goto wdGoToBookmark, , , "Обращение"
    .Application.Selection.InsertAfter (Text)
           
    Text = Cells(2, 11).Text
    .Application.Selection.Goto wdGoToBookmark, , , "Должность_подписант"
    .Application.Selection.InsertAfter (Text)
    
    Text = Cells(2, 10).Text
    .Application.Selection.Goto wdGoToBookmark, , , "Подписант"
    .Application.Selection.InsertAfter (Text)
    
    Text = Cells(1, 10).Text
    .Application.Selection.Goto wdGoToBookmark, , , "Исполнитель"
    .Application.Selection.InsertAfter (Text)
    
    Text = Cells(1, 11).Text
    .Application.Selection.Goto wdGoToBookmark, , , "Телефон"
    .Application.Selection.InsertAfter (Text)
    
    ActiveSheet.PivotTables("Заезжающие").PivotSelect _
        "'[#Inbox люди].[Фамилия Имя Отчество].[Фамилия Имя Отчество]'[All]", _
        xlLabelOnly + xlFirstRow, True
    Selection.Copy
    .Application.Selection.Goto wdGoToBookmark, , , "Список"
    .Application.Selection.PasteAndFormat (wdFormatPlainText)
    
    .SaveAs2 Filename:=("D:_______ & Format(Now, "yyyy-mm-dd hh-mm-ss") & ".docx"), _
    FileFormat:=wdFormatXMLDocument, AddtoRecentFiles:=False
    
    .Close
End With

wdApp.Quit

End Sub

Изменено: Сергей Редькин19.01.2022 10:39:43

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

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

This post is the second in a series about controlling other applications from Excel using VBA. In the first part we looked at the basics of how to reference other applications using Early Binding or Late Binding. In this post, we will look at how we can automate Word from Excel even though we don’t know any VBA code for Word… yet. The process we will use for this is as follows:

  1. Enable the Word Developer menu
  2. Record a Word macro
  3. Add the code to Excel VBA and amend
  4. Record macros in Excel if necessary
  5. Repeat the previous steps until macro complete

I am not an Excel VBA expert (I’m more of an Excel VBA tinkerer), and I am certainly not a Word VBA expert. The process I am about to show you may not create the most efficient code, but I know this process works, because I have used it myself to automate lots tasks using Microsoft Word.

Enable the Word Developer menu

If you have enabled the Excel Developer menu it is the same process in Word.

In Word: File -> Options -> Customize Ribbon

Then tick the Developer Ribbon option, OK.

Enable Word Developer Tab

Record a Word Macro

The key to the success of this method is taking small sections of code and building up a complex macro bit by bit. Using the Word Macro Recorder is again, similar to the Excel Macro recorder.

Click on: Developer -> Record Macro

Word VBA Record Macro

For the example in this post, we will create a macro which will open a new Word document, then copy a chart from Excel and paste it into that Word document. We will tackle this one stage at a time. Firstly, lets create the macro to open a new word document.

Click – Developer -> Record Macro. The Record Macro window will open.

Word Record Macro Window

Make a note of the “Store macro in” option, as we will need to know where to find the recorded code later. Normal.dotm is fine for now. Click OK – the Macro Recorder is now running.

Open a new Word Document – File -> New -> Blank Document

Stop the Macro from recording – Developer -> Stop Recording

Word VBA Stop Recording

We can now view the code for opening a new Word Document in the Visual Basic Editor. Click: Developer -> Visual Basic.

Word Visual Basic Editor

Find the location of your recorded code in the Visual Basic Editor. In this example: Normal -> Modules -> NewMacros.

Automate Word from Excel

Your code should look like the following. It may be slightly different, but not significantly.

Sub Macro1()
'
' Macro1 Macro
'
'
    Documents.Add Template:="Normal", NewTemplate:=False, DocumentType:=0
    Windows("Document1").Activate
    Windows("Document2").Activate
End Sub

Add the code to Excel VBA and amend

Let’s head back to the Excel VBA Editor and use the Early Binding method to control to Microsoft Word. In the Visual Basic Editor click Tools -> References select Microsoft Word x.xx Object Library. Then click OK.

VBA Word Object Library

As we are using Early Binding we need to declare the Application as a variable as follows:

Dim WordApp As Word.Application
Set WordApp = New Word.Application

Now copy and paste the code from the Word VBA Editor into the Excel VBA Editor.

The Word VBA code started with Documents.Add, all we have to do is add our application variable to the front of that line of code. Now becomes WordApp.Documents.Add . . .

Often, Selecting and Activating Objects is not required in VBA code, so I have not copied those statements into the code below.

Sub CreateWordDocument()

'Connect using Early Binding.
'Remember to set the reference to the Word Object Library
'In VBE Editor Tools -> References -> Microsoft Word x.xx Object Library
Dim WordApp As Word.Application
Set WordApp = New Word.Application

WordApp.Documents.Add Template:="Normal", NewTemplate:=False, DocumentType:=0
WordApp.Visible = True 'New Apps will be hidden by default, so make visible

Set WordApp = Nothing 'release the memory

End Sub

A point to note, when an application is opened with VBA, it is normally opened in the background. To make the Word document visible I have added the following code:

WordApp.Visible = True

Record macros in Excel (if necessary)

If we want to copy Excel content into a Word document, we will need to copy that content using Excel VBA. We can use the Macro Recorder in Excel to obtain the VBA code for copying, then we can use the Word Macro Recorder to obtain the VBA code for pasting.

Macro Recording from Excel – selecting a worksheet and copying chart

Sheets("Sheet1").Select
ActiveSheet.ChartObjects("Chart 1").Activate
ActiveChart.ChartArea.Copy

Macro Recording from Word – pasting a chart into a document

Selection.PasteSpecial Link:=False, DataType:=wdPasteEnhancedMetafile, _
        Placement:=wdInLine, DisplayAsIcon:=False

We can add both Macro recordings into our Excel macro. Remember to add WordApp. at the start of each statement of Word VBA code.

Sub CreateWordDocument()

'Connect using Early Binding.
'Remember to set the reference to the Word Object Library
'In VBE Editor Tools -> References -> Microsoft Word x.xx Object Library
Dim WordApp As Word.Application
Set WordApp = New Word.Application

WordApp.Documents.Add Template:="Normal", NewTemplate:=False, DocumentType:=0
WordApp.Visible = True 'New Apps will be hidden by default, so make visible

'code copied from Excel Macro recorder
Sheets("Sheet1").Select
Selection.ChartObjects("Chart 1").ChartArea.Copy

'code copied from Word Macro recorder with WordApp. added to the front.
WordApp.Selection.PasteSpecial Link:=False, DataType:=wdPasteEnhancedMetafile, _
        Placement:=wdInLine, DisplayAsIcon:=False

Set WordApp = Nothing 'release the memory 

End Sub

This code is not particularly efficient; it contains a few unnecessary sections code. However… it works!

Repeat the previous steps until macro complete

By repeating the same steps above; recording short actions, then transferring the code into Excel, we can slowly build up much more complex Macros. The key is to keep the actions short, if you do too many actions with the Macro Recorder, code starts to look long and scary.

If you’ve you tried to use the Macro Recorder before you will know that this is not as easy as it seems. And this simple tutorial may make you think it is easy, when it’s not. Sometimes, it can be quite frustrating trying to find out where the issues and errors are. The key to success is recording very short actions, such as those below and copying them into the Visual Basic Editor.

'Pressing the Enter Key to move to a new line in Word
WordApp.Selection.TypeParagraph

'Turn on/off Bold Text
WordApp.Selection.Font.Bold = wdToggle

'Change Font Size
WordApp.Selection.Font.Size = 16

'Type some text
WordApp.Selection.TypeText Text:="Here is some text"

You will soon build up a standard library of code that you can use to control Word for most basic tasks.

In recorded VBA code from Word, the word “Selection” in the code often refers to the document itself. It is possible to make the code a little bit more efficient by declaring the document as a variable. If we were opening a specific document, we could include this at the start, just below the declaration of the application.

'Declare a specific document as a variable
Dim WordDocument As Object
Set WordDocument = WordApp.Documents.Open(sourceFileName)

Or, if we created a new document we could include the following below the declaration of the application variable.

'Delcare a new document as a variable
Dim WordDocument As Object
Set WordDocument = WordApp.Documents.Add Template:="Normal", _
NewTemplate:=False, DocumentType:=0

If we have created the document as a variable we can then reference the specific document. This code:

WordApp.Selection.TypeParagraph

Would become this code:

WordDocument.TypeParagraph

Or this code:

WordApp.Selection.TypeText Text:="Here is some text"

Would become this code:

WordDocument.TypeText Text:="Here is some text"

This method is much better, as it doesn’t rely on the Selection of the user being in the right place.

Conclusion

We have seen in this post that it is possible to create complex Macros to automate Word from Excel using VBA. By understanding how to declare variables for the application and documents we can create much more robust macros, even without knowing a lot of VBA code.

Related Posts:

  • 5 quick ways to embed a Word document in Excel
  • Controlling Powerpoint from Excel using VBA
  • Edit links in Word using VBA
  • How to link Excel to Word

Headshot Round

About the author

Hey, I’m Mark, and I run Excel Off The Grid.

My parents tell me that at the age of 7 I declared I was going to become a qualified accountant. I was either psychic or had no imagination, as that is exactly what happened. However, it wasn’t until I was 35 that my journey really began.

In 2015, I started a new job, for which I was regularly working after 10pm. As a result, I rarely saw my children during the week. So, I started searching for the secrets to automating Excel. I discovered that by building a small number of simple tools, I could combine them together in different ways to automate nearly all my regular tasks. This meant I could work less hours (and I got pay raises!). Today, I teach these techniques to other professionals in our training program so they too can spend less time at work (and more time with their children and doing the things they love).


Do you need help adapting this post to your needs?

I’m guessing the examples in this post don’t exactly match your situation. We all use Excel differently, so it’s impossible to write a post that will meet everybody’s needs. By taking the time to understand the techniques and principles in this post (and elsewhere on this site), you should be able to adapt it to your needs.

But, if you’re still struggling you should:

  1. Read other blogs, or watch YouTube videos on the same topic. You will benefit much more by discovering your own solutions.
  2. Ask the ‘Excel Ninja’ in your office. It’s amazing what things other people know.
  3. Ask a question in a forum like Mr Excel, or the Microsoft Answers Community. Remember, the people on these forums are generally giving their time for free. So take care to craft your question, make sure it’s clear and concise.  List all the things you’ve tried, and provide screenshots, code segments and example workbooks.
  4. Use Excel Rescue, who are my consultancy partner. They help by providing solutions to smaller Excel problems.

What next?
Don’t go yet, there is plenty more to learn on Excel Off The Grid.  Check out the latest posts:

Referencing Word and other applications in Excel VBA

Part three of a four-part series of blogs

Even if you’re writing Visual Basic macros within Excel, there’s nothing to stop you inserting text into Word documents, manipulating PowerPoint slides or sending Outlook emails. This blog explains how to reference other applications, and write macros in Excel to link to other Microsoft Office software

  1. Creating References to Other Applications in VBA
  2. Using Tools References to Create a Reference to Word
  3. Using VBA to Link Applications (this blog)
  4. Using Bookmarks to Fill in a Word Document from Excel

This blog is part of a complete Excel VBA tutorial. You can also learn to program in VBA on one of our VBA macros courses.

Posted by
Andy Brown
on 05 December 2011

You need a minimum screen resolution of about 700 pixels width to see our blogs. This is because they contain diagrams and tables which would not be viewable easily on a mobile phone or small laptop. Please use a larger tablet, notebook or desktop computer, or change your screen resolution settings.

To get our program to work, we first need to create a reference to a new
instance of Word, then use this to create a document.  Finally, we need to
loop over our cells typing the values of each into this new Word document.

Creating a New Instance of Word

The first thing to do is to create a reference to a new Word application in
memory.  We’ll store this reference in a variable.  You can do this in
one of two ways.  The first way is easier to understand:

Dim WordApp As Word.Application

Set WordApp = New Word.Application

However, the second way is easier to write:

Dim WordApp As New Word.Application

So which is better?  The short answer is the second one, I think,
because it’s simpler — but it does have implications.  What follows is
a fairly technical summary of what these are.

Using the NEW Keyword — Pros and Cons

Consider the following line of code:

Dim WordApp As New Word.Application

This does not set the variable to a reference to Word, it just means that the variable will be set to a reference to Word the first time that it is used.
There are two small disadvantages to this:

  1. There is a slight overhead as the variable is checked to see
    if WordApp is Nothing every
    time it is used;
  2. Consequently you can never explicitly test if WordApp
    is Nothing because the instant you do, the variable is instantiated.

IMHO you don’t need to worry about this, but at the owlery we try not to
gloss over things!

Making an Application Visible

The next thing to do is to make sure that you can see the copy of Word:

You might be wondering why this is necessary.  When you create a copy of
an application in VBA, it isn’t automatically visible.  Had you missed out
this line, you would have had to press ALT + CTRL
+ DEL to list out running processes to close it
down:

Task Manager showing Word process

Select the running copy of MS Word — called WINWORD.EXE
— and end the process.

Note that the copy of Word you’ve created programmatically will
NOT show up in the Applications
tab of this dialog box.

Writing Code within the «Foreign» Application

Once you have created a copy of Word within memory, you can run commands
within this.  Here is what our full macro could look like:

Sub ListJugglersInWord()

Dim WordApp As New Word.Application

WordApp.Visible = True

Dim doc As Word.Document

Set doc = WordApp.Documents.Add

Dim JugglerRange As Range

Dim JugglerCell As Range

Set JugglerRange = Range( _

Range(«A1»), Range(«A1»).End(xlDown))

For Each JugglerCell In JugglerRange

WordApp.Selection.TypeText JugglerCell.Value

WordApp.Selection.TypeParagraph

Next JugglerCell

MsgBox «You should now see your jugglers in Word!»

End Sub

The commands to type information into Word are:

WordApp.Selection.TypeText JugglerCell.Value

WordApp.Selection.TypeParagraph

It is vital that you include the WordApp object at the start
of every Word VBA command, as explained below.

The Importance of Including the Application Prefix

Supposing that you had missed out the WordApp object from
the 2 lines shown above, to get:

Selection.TypeText JugglerCell.Value

Selection.TypeParagraph

This will not compile or run — here’s why.  When Excel sees the word
Selection, it tries to find this in its list of referenced
object libraries:

List of references in order

Excel will start from the top and work its way down in order. It will find the word
Selection within the Excel object library before it finds it within the Word one, and so assume that this is a built-in Excel object.

Because Excel is above Word in the list of references, the compiler will assume
that Selection refers to the currently selected cells in Excel,
and complain loudly that you can not apply the TypeText method
to an Excel range:

Error message - property or method not supported

The error message you will get if you try to run the macro without
prefixing the Word Selection object.

In theory you could change the order of the references to put Word above
Excel, but apart from being terrible practice — after all, you’re coding within
Excel — this isn’t actually possible (you get an error message if you try to
demote Excel in the references list).

Now we’ve got all of the theory out of the way, let’s look at a worked
example of how to get an Excel workbook to fill in a Word form.

This blog has 0 threads

Add post

This may further explain why the code works some times and not others.

My observation on the situation of the command

'Set wordAppxxxx = CreateObject("Word.Application.xx")'

working or not on your computer is that it is a function of the latest update you get from Microsoft.

Why I believe this:

I have an application that converts a text file to a Word document for backwards compatibility with some legacy apps. The best plan includes using a version of Word similar to the version the legacy apps were designed with/to. As a result, I searched on how to invoke a legacy version of Word as opposed to the default offering on my computer which is Word 2010.

The solution noted in this discussion chain provided the answer to my question. (Thank you Stack Overflow contributors!) I wanted to use Word XP, so I looked at my directories and observed that Word XP (aka Word 2002) is a member of Office 10, so I created the command

'Set wordApp2002 = CreateObject("Word.Application.10")'

and my program launched Word 2002 and the world was a happy place.

Over the weekened, I had an update to my computer. I control the updates via an app which gives me control over when updates occur such that I can observe changes to my configuration. This morning (9/30/13) I turned on a computer that had a Word update. I did not know this until after I had made one run of my app from last week. The app ran fine and invoked Word 2002 as expected.

But then I got the banner page informing me of a Word 2010 update that was installing itself.

Afterwards, I ran the app that worked so well for me last week and once today. Now, after the Word update (immediately after!), the same code now launches Word 2010 despite the fact that the command line invoking Word 2002 has not changed.

This appears strong evidence that a Microsoft update tweaked the settings that previously allowed the VB code to work as expected. This might be a good item to bring to Microsoft’s attention so see if we can get this item stabilized in subsequent update packages to allow consistent behavior in future releases.

I hope this is helpful,

JeffK

Сестра_Ветра

0 / 0 / 0

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

Сообщений: 91

1

28.11.2011, 14:37. Показов 3782. Ответов 5

Метки нет (Все метки)


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

Помогите с работой в Word.
Задание следующее:
Создать приложение, которое будет запускать Word, создавать новый документ, добавлять в него пару строк и таблицу. Таблица должна быть заполнена некоторыми данными. После добавления таблицы должна добавляться еще одна, в которой будут заполнены одна-две ячейки. После второй таблицы следует добавить некоторый текст, проверить правописание, и если проверка прошла успешно, отобразить документ в режиме предварительного просмотра печати.
Остановилась на том, что пытаюсь добавить вторую таблицу и заполнить её.

Visual Basic
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
'Создаем новый экземпляр сервера автоматизации Word
        Dim MyWord As New Word.Application
        Dim My_Table As Word.Table
        Dim My_Table2 As Word.Table
        Dim WdLine As Integer
        WdLine = 5
        'Dim My_Range As Word.Range
        'Делаем программу Word видимой
        MyWord.Visible = True
        'Добавляем в Word новый документ
        MyWord.Documents.Add()
        'Вставляем в документ строку
        MyWord.ActiveDocument.Range.InsertAfter("Отчет: " + MyWord.ActiveDocument.FullName + " по дисциплине Информационные технологии")
        MyWord.ActiveDocument.Paragraphs.Add()
        MyWord.ActiveDocument.Paragraphs.Add()
        MyWord.Selection.TypeText("Изученные темы представлены в данной таблице:")
        MyWord.ActiveDocument.Paragraphs.Add()
        My_Table = MyWord.ActiveDocument.Tables.Add(MyWord.ActiveDocument.Range, 4, 2)
        My_Table.Cell(1, 1).Range.Text = "Содержание"
        My_Table.Cell(1, 2).Range.Text = "Объем"
        My_Table.Cell(2, 1).Range.Text = "Работа с формами"
        My_Table.Cell(2, 2).Range.Text = "4 страницы"
        My_Table.Cell(3, 1).Range.Text = "Базовые конструкции языка "
        My_Table.Cell(3, 2).Range.Text = "9 страниц"
        My_Table.Cell(4, 1).Range.Text = "Обработка ошибок"
        My_Table.Cell(4, 2).Range.Text = "1 страница"
        MyWord.ActiveDocument.Paragraphs.Add()
        My_Table2 = MyWord.ActiveDocument.Tables.Add(MyWord.ActiveDocument.Range, 2, 2)
        My_Table2.Cell(1, 1).Range.Text = "Тема реферата"
        My_Table2.Cell(1, 2).Range.Text = "Экстремальное программирование"
        My_Table2.Cell(2, 1).Range.Text = "Дата защиты"
        My_Table2.Cell(2, 2).Range.Text = "1 декабря"
        'My_Table.Cell(1, 1).Borders(Word.WdBorderType.wdBorderTop).Color = Word.WdColor.wdColorBrown
        'Удаляем экземпляр сервера автоматизации Word
        MyWord = Nothing

Ошибок не выдает, и фактически всё работает.
Но!!!! Сначала появляются две строки текста, затем на его месте — таблица, затем на её месте — вторая таблица.
В общем, после всех действий в документе остается только одна последняя! таблица.
Нельзя ли сделать так, что вновь добавленные фрагменты не заменяли предыдущие, а накладывались ниже?



0



auts

13 / 13 / 0

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

Сообщений: 44

28.11.2011, 17:06

2

Используй для создания команду:

Visual Basic
1
Set TableWord = DocWord.Tables.Add(DocWord.Application.Selection.Range, x, y)

она добавляет таблицу туда где стоит курсор, а не заменяет.
tot полезная команда — это выделить конечную ячейку, а затем сместить курсор вправо, т.е. ровно под таблицу:

Visual Basic
1
2
TableWord.Cell(x, y).Select 'тут мы выделяем последнюю ячейку
DocWord.Application.Selection.MoveRight wdCharacter, 1 'тут мы перемещаем курсор вправо на 1

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



0



Сестра_Ветра

0 / 0 / 0

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

Сообщений: 91

28.11.2011, 18:22

 [ТС]

3

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

Используй для создания команду:

Visual Basic
1
Set TableWord = DocWord.Tables.Add(DocWord.Application.Selection.Range, x, y)

она добавляет таблицу туда где стоит курсор, а не заменяет.
tot полезная команда — это выделить конечную ячейку, а затем сместить курсор вправо, т.е. ровно под таблицу:

Visual Basic
1
2
TableWord.Cell(x, y).Select 'тут мы выделяем последнюю ячейку
DocWord.Application.Selection.MoveRight wdCharacter, 1 'тут мы перемещаем курсор вправо на 1

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

ругается на wdCharacter



0



13 / 13 / 0

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

Сообщений: 44

28.11.2011, 23:33

4

Нужно подгрузить библиотеку ворда:
project-reference-microsoft word 14 object library (14 если у вас 2010й офис)



0



0 / 0 / 0

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

Сообщений: 91

29.11.2011, 08:12

 [ТС]

5

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

Нужно подгрузить библиотеку ворда:
project-reference-microsoft word 14 object library (14 если у вас 2010й офис)

нет, офис у меня 2007.
Ругается студия на wdCharacter



0



auts

13 / 13 / 0

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

Сообщений: 44

29.11.2011, 09:38

6

а у вас приложения ворда активно на данный момент? может проблема в том что когда надо сдвинуть курсор — ворд или закрыт или неактивен?
в начале я прописываю:

Visual Basic
1
2
3
Dim WordApp As Word.Application ' экземпляр приложения ворда
Dim DocWord As Word.Document    ' экземпляр документа ворда
Dim TableWord As Word.Table     ' экземпляр таблицы ворда

а потом:

Visual Basic
1
2
3
4
Set WordApp = New Word.Application
  WordApp.Visible = False 'в режиме отладки тут лучше поставить тру, т.к. все наглядно и пошагово видно как все происходит
  Set DocWord = WordApp.Documents.Add
  DocWord.Activate

если это не поможет — не знаю))) я сам недавно стал бейсик изучать, но конкретно по этой теме.
З.Ы. не читал правила форума, поэтому не знаю, можно ли кидать ссылки на информацию вне форума и т.п. Есть очень полезная статейка в интернете как раз с взаимодействием с вордом через VB



1



IT_Exp

Эксперт

87844 / 49110 / 22898

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

Сообщений: 92,604

29.11.2011, 09:38

Помогаю со студенческими работами здесь

Консольное приложение. Создать меню, которое будет располагаться по середине
Всем привет. Как всегда курсовая :wall: Нужно создать меню, которое будет располагаться по…

Необходимо создать приложение, которое будет автоматически обновляться с API
Мне необходимо создать сайт, который извлекает данные из биржи по API. Мне нужно чтобы серверная…

Создать приложение, которое будет работать даже при выключенном компьютере
которая будет помогать браузерному дополнению imacros работать даже при выключенном компе. Вы мне…

Программа в Delphi 10 Seattle. Создать приложение, которое будет выводить изображение домика
Создать приложение, которое будет выводить изображение домика.

Приложение, которое будет на ПК уведомлять об уведомлениях на телефоне
Как &quot;отлавливать&quot; уведомления всех приложений?
Хочу сделать приложение, которое будет на ПК…

PHP приложение которое будет собират информация с других сайтов
Доброе утро! Люди, дайте совет: как написать php приложение которое будет собират информация…

Искать еще темы с ответами

Или воспользуйтесь поиском по форуму:

6

To write to a word file using Excel we need to access the word application using Excel VBA. In this tutorial we will learn how to open a word application, add a document and write content to it using Excel.

We have learned about the CreateObject method. In this article, we will use that method to create an object of word application instead of using the reference of it. So let’s get started with the tutorial.

The Process Of Writing To A Word File Using Excel VBA

To write a word file using VBA, we first need to open the Word Application of course. Then add a document to it. Select the paragraph and write the text to it. Each of these steps can be done easily from Excel. You will not need to interact with the Word document.

Let’s get started with an example without getting any further into theory. Because Iron Man said, «Sometimes you gotta run before you can walk».

Example 1: Write a given string to a Word Document from Excel

Sub WriteToWord()

   ''Using Early Binding

    'Dim wordApp As Word.Application

    'Dim mydoc As Word.Document

    'set  wordApp=new word.Application

        

    'Using late binding to create word application object

    

    'Declaring variables as objects

    Dim wordApp As Object

    Dim mydoc As Object

    

    'Initializing the object using CreateOBject Function

    Set wordApp = CreateObject("Word.Application")

    

    'Making word App Visible

    wordApp.Visible = True

   

    'Creating a new document

    Set mydoc = wordApp.Documents.Add()


    

    'Getting input from user

    myString = Application.InputBox("Write Your Text")

    

    'Writing to word

    wordApp.Selection.TypeText Text:=myString

    'inserting a new paragraph

    wordApp.Selection.TypeParagraph


End Sub

Explanation of the Code:

Well I have explained each step in the code itself using comments but let’s have some word about the lines we have used in this sub.

So this VBA code takes input from the user and writes to a new word document. 

The first few lines are commented out. These lines are using Late binding. If you have given reference to the word application you can remove the commenting tag. The code we are processing is using late binding. I have explained it in this article. You can refer to it to understand what is late binding and early binding in Excel VBA.

    ‘Declaring variables as objects

    Dim wordApp As Object

    Dim mydoc As Object

Here we have declared two variables of type Object. The Object type variable can hold any type of object.

    ‘Initializing the object using CreateOBject Function

    Set wordApp = CreateObject(«Word.Application»)

    ‘Making word App Visible

    wordApp.Visible = True

    ‘Creating a new document

    Set mydoc = wordApp.Documents.Add()

In the first line above, we are intentiating the wordApp variable with an object of type Word.App using the CreateObject method. This will open the Word Application.

In the second line we are making the word application visible so that we can work with it.

In the next line, we add a new document to the word application using Word.Documents.Add() function. This is stored in the mydoc variable.

    ‘Getting input from user

    myString = Application.InputBox(«Write Your Text»)

Here we are simply getting input from the user using the InputBox function of Application Class. And we are storing the input in the mystring variable.

    ‘Writing to word

    wordApp.Selection.TypeText Text:=myString

    ‘inserting a new paragraph

    wordApp.Selection.TypeParagraph

Finally, we are using the TypeText method of Word Application.Selection class to write to the document. The last line enters into a new paragraph.

So yeah guys, this is how you can create a new Word document and write to it using Excel VBA. I have not gone into details as it would make the article exhaustingly long. This was only to learn how you can write to a word document through Excel. I hope it helped you understand the process. If you have any questions regarding this article, you can contact me through the comments section below.

Related Articles:

Getting Started With Excel VBA UserForms| I will explain how to create a form in excel, how to use VBA toolbox, how to handle user inputs and finally how to store the user inputs. We will go through these topics using one example and step by step guide.

VBA variables in Excel| VBA stands for Visual Basic for Applications. It is a programming language from Microsoft. It is used with Microsoft Office applications such as MSExcel, MS-Word and MS-Access whereas VBA variables are specific keywords.

Excel VBA Variable Scope| In all the programming languages, we have variable access specifiers that define from where a defined variable can be accessed. Excel VBA is no Exception. VBA too has scope specifiers.

ByRef and ByVal Arguments | When an argument is passed as a ByRef argument to a different sub or function, the reference of the actual variable is sent. Any changes made into the copy of the variable, will reflect in the original argument.

Delete sheets without confirmation prompts using VBA in Microsoft Excel | Since you are deleting sheets using VBA, you know what you are doing. You would like to tell Excel not to show this warning and delete the damn sheet.

Add And Save New Workbook Using VBA In Microsoft Excel 2016| In this code, we first created a reference to a workbook object. And then we initialized it with a new workbook object. The benefit of this approach is that you can do operations on this new workbook easily. Like saving, closing, deleting, etc

Display A Message On The Excel VBA Status Bar| The status bar in excel can be used as a code monitor. When your VBA code is lengthy and you do several tasks using VBA, you often disable the screen update so that you don’t see that screen flickering.

Turn Off Warning Messages Using VBA In Microsoft Excel 2016| This code not only disables VBA alerts but also increases the time efficiency of the code. Let’s see how.

Popular Articles:

50 Excel Shortcuts to Increase Your Productivity | Get faster at your task. These 50 shortcuts will make you work even faster on Excel.

The VLOOKUP Function in Excel | This is one of the most used and popular functions of excel that is used to lookup value from different ranges and sheets. 

COUNTIF in Excel 2016 | Count values with conditions using this amazing function. You don’t need to filter your data to count specific values. Countif function is essential to prepare your dashboard.

How to Use SUMIF Function in Excel | This is another dashboard essential function. This helps you sum up values on specific conditions.

Содержание

  • 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>
  • Remove From My Forums
  • Question

  • Why do I get Runtime Error 4218: Type Mismatch on the copy of FormattedText below, although the commented line works  (Word 2010, VBA)  ?

     With wordDoc

                    
                        Set newDocRange = .Range
                        newDocRange.Collapse wdCollapseEnd
                        ‘newDocRange.Text = origDocRange.Text  this works but formattedtext does not

                       

                        newDocRange.FormattedText = origDocRange.FormattedText

                        .SaveAs (newdocName)

                   

                    End With

Answers

  • Cindy,  I am having success with formattedtext if I do this where I prefix «WordApp» to this line as well as to destDoc.

    Set srcDoc = WordApp.Documents.Open(srcDocName, , , , , , , , , , , False)

    I see this from Ji.Zhou in Jan 4, 2008:

          FormattedText can only be set in the same Word Application. It will fail if the two documents are in different Word Application. Try these codes:

    So perhaps if within Access if I don’t do this then it really is 2 Word Apps  ?

    • Marked as answer by

      Thursday, December 23, 2010 2:10 PM

Skip to content

Interacting with Other Applications using VBA

We can Interacting with Other Applications using VBA- with the MS Office Applications like Word, PowerPoint,Outlook,etc… and other applications like Internet Explorer, SAS,etc.

In this Section:

  • Introduction?
  • How to interact with MS Word? – Late Binding
  • How to interact with MS Word? – Early Binding
  • How to interact with PowerPoint? – Early Binding
  • How to interact with Outlook? – Late Binding
  • Example File

Interacting with Other Applications using VBA – An Introduction:

Yes, we can interact with the other Applications using VBA,i.e; with the MS Office Applications like Word, PowerPoint,Outlook,etc… and other applications like Internet Explorer, SAS,etc…
to do this first we need to establish a connection with those applications, then we can able to access objects of the other applications from VBA.

Interacting with Other Applications using VBA

There are two ways to establish the Connection:Late binding and Early binding. In late binding, we will create an Object in run time it will assign the necessary object. In early binding, we have to refer the necessary object before we use it.

If you want to automate Other Microsoft Applications: You would declare the following variables at the top of your procedure, you need to declare some object variables specific to the application being automated.

(In early binding, first we need to set a reference to the Other application’s object library. In the Visual Basic Editor (VBE) => Select References… from the Tools menu => Select Other application’s object library)

Late Binding

Dim otherApp As Object
Dim otherDoc As Object
Dim otherSpecificObjects As Object

'To open a new instance of Other:
Set otherApp = CreateObject("Other.Application")

'Or to use an existing instance of Other:
Set otherApp = GetObject(, "Other.Application")

Early binding – wee need to add the reference for required object.

Dim otherApp As Other.Application
Dim otherDoc As Other.DocType
Dim otherSpecificObjects As Other.SpecificObjects

'To open a new instance of Other:
Set otherApp = CreateObject("Other.Application")

'Or to use an existing instance of Other:
Set otherApp = GetObject(, "Other.Application")

For example if you want to interact with MS Word Application, you have to write the code as follows:

Dim wordApp As Word.Application
Dim wordDoc As Word.Document

' Reference existing instance of Word
    Set wordApp = GetObject(, &amp;quot;Word.Application&amp;quot;)
' Reference active document
    Set wordDoc = wordApp .ActiveDocument   

How to interact with MS Word? (Early Binding)

The following example will show you how to interact with MS word Application from Excel VBA, it will create a new word document and add some text to the newly created document.

*Create a new module and Add the reference to Microsoft Word Object Library and then Paste the following code into the module and run (Press F5) it to test it.

Sub sbWord_CreatingAndFormatingWordDoc()

Dim oWApp As Word.Application
Dim oWDoc As Word.Document
Dim sText As String
Dim iCntr As Long
'
Set oWApp = New Word.Application
Set oWDoc = oWApp.Documents.Add() '(&amp;quot;C:DocumentsDoc1.dot&amp;quot;) 'You can specify your template here
'
'Adding new Paragraph
'
Dim para As Paragraph
Set para = oWDoc.Paragraphs.Add
'
para.Range.Text = &amp;quot;Paragraph 1 - My Heading: ANALYSISTABS.COM&amp;quot;
para.Format.Alignment = wdAlignParagraphCenter
para.Range.Font.Size = 18
para.Range.Font.Name = &amp;quot;Cambria&amp;quot;
'
For i = 0 To 2
Set para = oWDoc.Paragraphs.Add
para.Space2
Next
'
Set para = oWDoc.Paragraphs.Add
With para
.Range.Text = &amp;quot;Paragraph 2 - Example Paragraph, you can format it as per yor requirement&amp;quot;
.Alignment = wdAlignParagraphLeft
.Format.Space15
.Range.Font.Size = 14
.Range.Font.Bold = True
End With
'
oWDoc.Paragraphs.Add
'
Set para = oWDoc.Paragraphs.Add
With para
.Range.Text = &amp;quot;Paragraph 3 - Another Paragraph, you can create number of paragraphs like this and format it&amp;quot;
.Alignment = wdAlignParagraphLeft
.Format.Space15
.Range.Font.Size = 12
.Range.Font.Bold = False
End With
'
oWApp.Visible = True
End Sub

How to interact with MS Word? (Late Binding)

The following example will show you how to interact with MS word Application from Excel VBA, it will create a new word document and add some text to the newly created document.

Sub sbWord_CreatingAndFormatingWordDocLateBinding()

Dim oWApp As Object
Dim oWDoc As Object
Dim sText As String
Dim iCntr As Long
'
Set oWApp = New Word.Application
Set oWDoc = oWApp.Documents.Add() '(&amp;quot;C:DocumentsDoc1.dot&amp;quot;) 'You can specify your template here
'
'Adding new Paragraph
'
Dim para As Paragraph
Set para = oWDoc.Paragraphs.Add
'
para.Range.Text = &amp;quot;Paragraph 1 - My Heading: ANALYSISTABS.COM&amp;quot;
para.Format.Alignment = wdAlignParagraphCenter
para.Range.Font.Size = 18
para.Range.Font.Name = &amp;quot;Cambria&amp;quot;
'
For i = 0 To 2
Set para = oWDoc.Paragraphs.Add
para.Space2
Next
'
Set para = oWDoc.Paragraphs.Add
With para
.Range.Text = &amp;quot;Paragraph 2 - Example Paragraph, you can format it as per yor requirement&amp;quot;
.Alignment = wdAlignParagraphLeft
.Format.Space15
.Range.Font.Size = 14
.Range.Font.Bold = True
End With
'
oWDoc.Paragraphs.Add
'
Set para = oWDoc.Paragraphs.Add
With para
.Range.Text = &amp;quot;Paragraph 3 - Another Paragraph, you can create number of paragraphs like this and format it&amp;quot;
.Alignment = wdAlignParagraphLeft
.Format.Space15
.Range.Font.Size = 12
.Range.Font.Bold = False
End With
'
oWApp.Visible = True
End Sub

How to interact with MS PowerPoint?

'Add Microsoft PowerPoint Object Library
Sub sbPowePoint_SendDataFromExcelToPPT()

'Declarations
Dim oPPT As PowerPoint.Application
Dim oPPres As PowerPoint.Presentation
Dim oPSlide As PowerPoint.Slide
Dim sText As String


'Open PowerPoint
Set oPPT = New PowerPoint.Application
Set oPPres = oPPT.Presentations.Add
oPPT.Visible = True


'Add a Slide
Set oPSlide = oPPres.Slides.Add(1, ppLayoutTitleOnly)
oPSlide.Select

'Copy a range as a picture and align it
ActiveSheet.Range(&amp;quot;A3:E10&amp;quot;).CopyPicture Appearance:=xlScreen, Format:=xlPicture
oPSlide.Shapes.Paste


oPPT.ActiveWindow.Selection.ShapeRange.Align msoAlignCenters, True
oPPT.ActiveWindow.Selection.ShapeRange.Align msoAlignMiddles, True


'Add the title text
sText = &amp;quot;My Header - ANALYSISTABS.COM Example&amp;quot;
oPSlide.Shapes.Title.TextFrame.TextRange.Text = sText


oPPT.Activate


'Release Objects
Set oPSlide = Nothing
Set oPPres = Nothing
Set oPPT = Nothing
'
End Sub

How to interact with MS Outlook?

'Late Binding
Sub sbOutlook_SendAMail()
'Declaration
Dim oOApp As Object
Dim oMail As Object
'
Set oOApp = CreateObject(&amp;quot;Outlook.Application&amp;quot;)
Set oMail = oOApp.CreateItem(0)
'
On Error Resume Next
' Change the mail address and subject in the macro before you run it.
With oMail
.To = &amp;quot;userid@organization.com&amp;quot;
.CC = &amp;quot;&amp;quot;
.BCC = &amp;quot;&amp;quot;
.Subject = &amp;quot;Write Your Subject Here - Example mail - ANALYSISTABS.COM&amp;quot;
.Body = &amp;quot;Hi, This is example Body Text.&amp;quot;
'
'.Attachments.Add (&amp;quot;C:TempExampleFile.xls&amp;quot;) '=&amp;gt; To add any Attcahment
.Display '=&amp;gt; It will display the message
'.Send '=&amp;gt; It will send the mail
End With
On Error GoTo 0
'
Set oMail = Nothing
Set oOApp = Nothing
End Sub

Example File

You can download the example file here and explore it.

ANALYSIS TABS – Interacting With Other Applications

Effortlessly Manage Your Projects and Resources
120+ Professional Project Management Templates!

A Powerful & Multi-purpose Templates for project management. Now seamlessly manage your projects, tasks, meetings, presentations, teams, customers, stakeholders and time. This page describes all the amazing new features and options that come with our premium templates.

Save Up to 85% LIMITED TIME OFFER
Excel VBA Project Management Templates
All-in-One Pack
120+ Project Management Templates
Essential Pack
50+ Project Management Templates

Excel Pack
50+ Excel PM Templates

PowerPoint Pack
50+ Excel PM Templates

MS Word Pack
25+ Word PM Templates

Ultimate Project Management Template

Ultimate Resource Management Template

Project Portfolio Management Templates

Related Posts

    • Interacting with Other Applications using VBA – An Introduction:
    • How to interact with MS Word? (Early Binding)
      • *Create a new module and Add the reference to Microsoft Word Object Library and then Paste the following code into the module and run (Press F5) it to test it.
    • How to interact with MS Word? (Late Binding)
    • How to interact with MS PowerPoint?
    • How to interact with MS Outlook?
    • Example File
      • You can download the example file here and explore it.
      • ANALYSIS TABS – Interacting With Other Applications

VBA Reference

Effortlessly
Manage Your Projects

120+ Project Management Templates

Seamlessly manage your projects with our powerful & multi-purpose templates for project management.

120+ PM Templates Includes:

4 Comments

  1. Jasham
    July 10, 2015 at 3:52 AM — Reply

    Is there is a way to automate some other applications through Excel VBA like “Remote Desktop Connection” where we can automate the application which is present in some other system.

    For Example:-

    Machine X is my system & I want to open Google from the Y Machine.

    So is there is a way to automate the process.
    (Opening the Remote Desktop Connection application-> Then open Google from Y Machine.)

  2. Yaman
    January 23, 2017 at 7:42 PM — Reply

    Easier method :
    Use Selenium. Set port (ip if not on same LAN). Use the port in the remote PC with (–remote debugging) to open Chrome.

    Now your VBA will run on PC X and Chrome will run on PC Y.

    This assumes you can Open chrome on remote PC. If not simply use a runas command to get that done.

    Google SeleniumVBA for details.

  3. Rondiman
    February 21, 2017 at 11:21 PM — Reply

    Excelent!

    Could make a post about interaction with .pdf? that would be outstanding!

  4. Pandiarajan g
    April 6, 2017 at 12:50 PM — Reply

    I tried to execute the above query and i get this message “User-defined type not defined”…. Please guide me….

Effectively Manage Your
Projects and  Resources

With Our Professional and Premium Project Management Templates!

ANALYSISTABS.COM provides free and premium project management tools, templates and dashboards for effectively managing the projects and analyzing the data.

We’re a crew of professionals expertise in Excel VBA, Business Analysis, Project Management. We’re Sharing our map to Project success with innovative tools, templates, tutorials and tips.

Project Management
Excel VBA

Download Free Excel 2007, 2010, 2013 Add-in for Creating Innovative Dashboards, Tools for Data Mining, Analysis, Visualization. Learn VBA for MS Excel, Word, PowerPoint, Access, Outlook to develop applications for retail, insurance, banking, finance, telecom, healthcare domains.

Analysistabs Logo

Page load link

Go to Top

Like this post? Please share to your friends:
  • Dim wd as new word application
  • Dim excel что это такое
  • Dim excel workbook as excel workbook
  • Dim as new excel vba
  • Dim as integer excel