Call word from excel

I have two macros, one in Excel, and one in Word. The Excel Macro calls the Word macro. My code is as follows:

Excel:

Public wb1 As Workbook
Public dt1 As Document

Sub openword()
Dim wpath, epath As String      'where the word document will be opened and where the excel sheet will be saved
Dim wordapp As Object           'preparing to open word
Set wb1 = ThisWorkbook

While wb1.Sheets.Count <> 1
    wb1.Sheets(2).Delete
Wend

wpath = "C:usersGPerryDesktopProjects and Workdocument.docm"
Set wordapp = CreateObject("Word.Application")
'Set wordapp = CreateObject(Shell("C:Program Files (x86)Microsoft OfficeOffice14WINWORD", vbNormalFocus)) this is one I tried to make work because while word.application seems to work, I don't *understand* it, so if anyone can help, that'd be awesome
wordapp.Visible = True
Set dt1 = wordapp.Documents.Open(wpath)
wordapp.Run "divider", wb1, dt1
dt1.Close
wordapp.Quit
End Sub

And word:

Sub divider(wb1, dt1)
Set dt1 = ThisDocument
If dt1.Paragraphs.Count > 65000 Then
    Set cutrange = dt1.Range(dt1.Paragraphs(1).Range.Start, dt1.Paragraphs(65000).Range.End)
    If wb1.Sheets(Sheets.Count).Cells(1, 1) <> "" Then
        wb1.Sheets.Add After:=Sheets.Count
    End If
Else
    Set cutrange = dt1.Content
    If wb1.Sheets(Sheets.Count).Cells(1, 1) <> "" Then
        wb1.Sheets.Add After:=Sheets.Count
    End If
End If
    cutrange.Cut Destination:=wb1.Sheets(wb1.Sheets(Sheets.Count)).Cells(1, 1)
    wb1.Sheets(Sheets.Count).Cells(1, 1).TextToColumns Destination:=wb1.Sheets(1).Cells(1, 1)
End Sub

My problem is that the variable wb1 isn’t getting passed between them. Even though I put wb1 in the list of variables to send to the macro, when it arrives at the document, wb1 has no value inside of it. I would re-initialize it, but I don’t know how to refer to an already existing document — only how to set it equal to one as you open it.

So either how do I pass the value through into the Word macro, or how do I re-initialize this variable? Preferably without having to set something equal to the excel application, because every time I try that it sets it equal to Excel 2003, not 2010 (though any solutions to that are also, of course, welcome).

Thanks!

  • #1

I am trying to call a word macro from in excel. If I ignore any variables, then it works. However, when I include any variables, it fails.

Public Sub doQuote()

‘Create the quote
Dim wdApp As Object
Dim wdDoc As Object
Set wdApp = CreateObject(«Word.Application»)
Set wdDoc = wdApp.Documents.Open(ThisWorkbook.Path & «NCR Form.dot»)
wdApp.Visible = True

‘This Works
wdApp.Run («test»)

‘These Fail (Object doesnt support this property)
wdApp.Run («test(«»Str»»)»)
wdApp.Run «test(«»Str»»)»
S = «str»
wdApp.Run («test(S)»)
wdApp.Run «test(S)»

‘This wont compile (.NET way of doing things)
wdApp.Run («test», «Str»)

Set wdApp = Nothing
Set wdDoc = Nothing

End Sub

Basically I’ve tried everything I can find and nothing seems to work as wanted. Any help would be awesome.

Thanks

Last edited: May 31, 2010

  • 02-13-2006, 05:41 AM


    #1

    Call word from excel

    Hello!

    My macro doesn`t work, maybe anyone could help me???
    I have to write a macro in Excel, that should open a Word document,
    looking for a word (last month) and replace it with the actual month. (My code has problems with the selection and search)
    Then it should replace numbers in the word document against numbers from my excel sheet.
    Please help me!!!
    [vba]
    Sub Word()
    Dim wdAnw As Object
    Dim wdDok As Object

    Application.ScreenUpdating = False

    letztes_datum = InputBox(«Bitte geben sie das letzte Pr?fdatum ein, » & _
    «damit der Monat durch den aktuellen Monat ersetzt » & _
    «werden kann!», «letztes Pr?fdatum», 6250, 6150)
    letzter_monat = Monat(letztes_datum)
    akt_datum = Date
    akt_monat = Monat(akt_datum)

    If letzter_monat = 1 Then
    letzter_monat = «Januar»
    ElseIf letzter_monat = 2 Then
    letzter_monat = «Februar»
    ElseIf letzter_monat = 3 Then
    letzter_monat = «M?rz»
    ElseIf letzter_monat = 4 Then
    letzter_monat = «April»
    ElseIf letzter_monat = 5 Then
    letzter_monat = «Mai»
    ElseIf letzter_monat = 6 Then
    letzter_monat = «Juni»
    ElseIf letzter_monat = 7 Then
    letzter_monat = «Juli»
    ElseIf letzter_monat = 8 Then
    letzter_monat = «August»
    ElseIf letzter_monat = 9 Then
    letzter_monat = «September»
    ElseIf letzter_monat = 10 Then
    letzter_monat = «Oktober»
    ElseIf letzter_monat = 11 Then
    letzter_monat = «November»
    ElseIf letzter_monat = 12 Then
    letzter_monat = «Dezember»
    End If

    If akt_monat = 1 Then
    akt_monat = «Januar»
    ElseIf akt_monat = 2 Then
    akt_monat = «Februar»
    ElseIf akt_monat = 3 Then
    akt_monat = «M?rz»
    ElseIf akt_monat = 4 Then
    akt_monat = «April»
    ElseIf akt_monat = 5 Then
    akt_monat = «Mai»
    ElseIf akt_monat = 6 Then
    akt_monat = «Juni»
    ElseIf akt_monat = 7 Then
    akt_monat = «Juli»
    ElseIf akt_monat = 8 Then
    akt_monat = «August»
    ElseIf akt_monat = 9 Then
    akt_monat = «September»
    ElseIf akt_monat = 10 Then
    akt_monat = «Oktober»
    ElseIf akt_monat = 11 Then
    akt_monat = «November»
    ElseIf akt_monat = 12 Then
    akt_monat = «Dezember»
    End If

    Application.ActivateMicrosoftApp xlMicrosoftWord

    Const pfad = «M:Investment-ControllingprivatJudithMonatsreport_Performance_2006.doc»

    Set wdDok = GetObject(pfad)
    Set wdAnw = wdDok.Parent
    wdAnw.Visible = True
    wdAnw.WindowState = 1
    wdDok.Activate

    ….??????
    Selection.Find.ClearFormatting ‘??
    With Selection.Find
    .Text = «Januar»
    .Replacement.Text = «»
    .Forward = True
    .Wrap = wdFindContinue
    .Format = False
    .MatchCase = False
    .MatchWholeWord = False
    .MatchWildcards = False
    .MatchSoundsLike = False
    .MatchAllWordForms = False
    End With
    Selection.Find.Execute
    With Selection.Find
    .Text = «Januar»
    .Replacement.Text = «Februar»
    .Forward = True
    .Wrap = wdFindContinue
    .Format = False
    .MatchCase = False
    .MatchWholeWord = False
    .MatchWildcards = False
    .MatchSoundsLike = False
    .MatchAllWordForms = False
    End With
    End Sub

    Function Monat(Datum)
    Monat = Month(Datum)
    End Function
    [/vba]
    Greetings, Judith


  • 02-13-2006, 08:42 AM


    #2

    Judith

    The way you have referred to the Selection I think will actually refer to the current selection in Excel, not Word.


  • 02-13-2006, 09:49 PM


    #3

    [VBA]
    Sub Word()
    Dim wdAnw As Object
    Dim wdDok As Object

    Application.ScreenUpdating = False

    letztes_datum = InputBox(«Bitte geben sie das letzte Pr?fdatum ein, » & _
    «damit der Monat durch den aktuellen Monat ersetzt » & _
    «werden kann!», «letztes Pr?fdatum», 6250, 6150)

    letzter_monat = Monat(letztes_datum)
    akt_datum = Date
    akt_monat = Monat(akt_datum)

    Select Case letzter_monat
    Case 1: letzter_monat = «Januar»
    Case 2: letzter_monat = «Februar»
    Case 3: letzter_monat = «M?rz»
    Case 4: letzter_monat = «April»
    Case 5: letzter_monat = «Mai»
    Case 6: letzter_monat = «Juni»
    Case 7: letzter_monat = «Juli»
    Case 8: letzter_monat = «August»
    Case 9: letzter_monat = «September»
    Case 10: letzter_monat = «Oktober»
    Case 11: letzter_monat = «November»
    Case 12: letzter_monat = «Dezember»
    End Select

    Select Case akt_monat
    Case 1: akt_monat = «Januar»
    Case 2: akt_monat = «Februar»
    Case 3: akt_monat = «M?rz»
    Case 4: akt_monat = «April»
    Case 5: akt_monat = «Mai»
    Case 6: akt_monat = «Juni»
    Case 7: akt_monat = «Juli»
    Case 8: akt_monat = «August»
    Case 9: akt_monat = «September»
    Case 10: akt_monat = «Oktober»
    Case 11: akt_monat = «November»
    Case 12: akt_monat = «Dezember»
    End Select

    Application.ActivateMicrosoftApp xlMicrosoftWord

    Const pfad = «M:Investment-ControllingprivatJudithMonatsreport_Performance_2006.doc»

    Set wdDok = GetObject(pfad)
    Set wdAnw = wdDok.Parent

    wdAnw.Visible = True
    wdAnw.WindowState = 1

    With wdDok
    .Activate

    .Selection.Find.ClearFormatting ‘??

    With .Selection.Find
    .Text = «Januar»
    .Replacement.Text = «»
    .Forward = True
    .Wrap = wdFindContinue
    .Format = False
    .MatchCase = False
    .MatchWholeWord = False
    .MatchWildcards = False
    .MatchSoundsLike = False
    .MatchAllWordForms = False
    End With

    .Selection.Find.Execute

    With .Selection.Find
    .Text = «Januar»
    .Replacement.Text = «Februar»
    .Forward = True
    .Wrap = wdFindContinue
    .Format = False
    .MatchCase = False
    .MatchWholeWord = False
    .MatchWildcards = False
    .MatchSoundsLike = False
    .MatchAllWordForms = False
    End With
    End With

    Set wdDok = Nothing
    Set wdAnw = Nothing
    End Sub

    Function Monat(Datum)
    Monat = Month(Datum)
    End Function

    [/VBA]


  • 02-14-2006, 12:06 AM


    #4

    Just an observation, we can get rid of a lot of lines of code.

    All this code:
    [vba]
    If letzter_monat = 1 Then
    letzter_monat = «Januar»
    ElseIf letzter_monat = 2 Then letzter_monat = «Februar»
    ElseIf letzter_monat = 3 Then
    letzter_monat = «M?rz»
    ElseIf letzter_monat = 4 Then
    letzter_monat = «April»
    ElseIf letzter_monat = 5 Then
    letzter_monat = «Mai»
    ElseIf letzter_monat = 6 Then
    letzter_monat = «Juni»
    ElseIf letzter_monat = 7 Then
    letzter_monat = «Juli»
    ElseIf letzter_monat = 8 Then
    letzter_monat = «August»
    ElseIf letzter_monat = 9 Then
    letzter_monat = «September»
    ElseIf letzter_monat = 10 Then
    letzter_monat = «Oktober»
    ElseIf letzter_monat = 11 Then
    letzter_monat = «November»
    ElseIf letzter_monat = 12 Then
    letzter_monat = «Dezember»
    End If

    If akt_monat = 1 Then
    akt_monat = «Januar»
    ElseIf akt_monat = 2 Then
    akt_monat = «Februar»
    ElseIf akt_monat = 3 Then
    akt_monat = «M?rz»
    ElseIf akt_monat = 4 Then
    akt_monat = «April»
    ElseIf akt_monat = 5 Then
    akt_monat = «Mai»
    ElseIf akt_monat = 6 Then
    akt_monat = «Juni»
    ElseIf akt_monat = 7 Then
    akt_monat = «Juli»
    ElseIf akt_monat = 8 Then
    akt_monat = «August»
    ElseIf akt_monat = 9 Then
    akt_monat = «September»
    ElseIf akt_monat = 10 Then
    akt_monat = «Oktober»
    ElseIf akt_monat = 11 Then
    akt_monat = «November»
    ElseIf akt_monat = 12 Then
    akt_monat = «Dezember»
    End If

    [/vba]

    Can be replaced with this code:

    [vba]
    letzter_monat = Format(DateSerial(1, letzter_monat, 1), «mmmm»)
    akt_monat = Format(DateSerial(1, akt_monat, 1), «mmmm»)
    [/vba]

    I do not know if these functions are valid with the language version of Excel that you have (German?), but they should have an equivalent.


  • 02-14-2006, 04:15 AM


    #5

    Good pickup Jake — I didn’t even think of it!


  • Call Word from Excel VBA — cannot CreateObject

    Hi all. I’m trying to copy a range of cells into an existing word file. Here’s my code:

    Sub test()
        Range("A2", Cells(19, 7)).Copy
        
        Dim WordApp As Object
        Dim SaveDirectory As String
        
        SaveDirectory = "C:UserstomDesktop" 
        
        Set WordApp = CreateObject("Word.Application")
        With WordApp 
            'You can uncomment these 2 lines to see the process
    '        .Visible = True
    '        .Activate
            
            .documents.Open ("C:UserstomDesktopcodecalendar.doc") 
            
            .Selection.EndKey Unit:=wdStory 'Move the insert point to the end of the .doc
            .Selection.PasteAppendTable 'Paste in the table as "Merge Table"
            
            .Selection.HomeKey Unit:=wdStory 'Move the insert point to the 1st row of the calendar, 
            .Selection.Rows.Delete 'Delte that empty row
            
            .ActiveDocument.SaveAs2 Filename:=SaveDirectory + "Final semester calendar for " + "Fall 2019" + ".docx" 
            .ActiveDocument.Close 'Close the .doc generated
            
        End With
        
        
    End Sub
    

    I am currently stuck on «Set WordApp = CreateObject(«Word.Application»)» and I just couldn’t pass through it. I kept getting the error of «Application-defined or object-defined error». I searched a lot but it seems like not too many people are calling Word from Excel so most posts are very old. I’m not sure whether I do it correctly since the tutorial I followed is also pretty old. Could someone help me with this problem? Thanks!

    Edit: sorry I forgot to mention that I have the option for «Microsoft Word 16.0 Object Library» checked already.

    2nd Edit: Solved the problem by myself. It turned out that if your word doc is a read-only document, you’d better use Set MyDoc = .Documents.Add rather than Set MyDoc = .Documents.Open. After that you can do the save as command.

    See all How-To Articles

    This tutorial demonstrates how to create a Word document from Excel or Google Sheets.

    wordsave intro

    Link From Excel to Word Using Paste Options

    1. In the Excel file, select the required data. Then in the Ribbon, select Home > Clipboard > Copy.

    wordsave copy

    1. Open Word and create a new document. In the Ribbon, select Home > Clipboard > Paste > Link and Keep Source Formatting.

    wordsave paste special link

    The selected Excel data is pasted into Word.

    Insert Excel Content as an Object Into Word

    1. With a Word document open, in the Ribbon, select Insert > Text > Object.

    wordsave insert object

    1. Select the Create from File tab.
      Then use the Browse… button to select the Excel file to be inserted into Word as an object.
      Finally, click OK to insert the object into the Word document.

    wordsave object

    The file contents are inserted into Word.

    wordsave word object

    Paste Unformatted Data From Excel to Word

    1. In Excel, highlight the range of cells you need to copy to Word.

    wordsave copy excel

    1. In the Ribbon, select Home > Clipboard > Copy.

    wordsave copyexcel ribbon

    1. Switch to an open Word document, or open Word and create a new document.
    2. In the Ribbon, select Home > Clipboard > Paste > Paste Special.

    wordsave pastespecial

    1. Select Unformatted Unicode Text form the Paste option, and then click OK.

    wordsave unformatted text

    The data from Excel is pasted into Word as raw data (not in a table).

    wordsave unformatted word

    Create a Word Document From Google Sheets

    You can copy and paste between a Google sheet and Word document the same way as in Excel.

    1. Select the range of cells in the Google sheet and press CTRL + C to copy the range of cells.

    wordsave gs copy

    1. Open Word and create a new document.
    2. In the Ribbon, select Home > Clipboard > Paste to paste the range of cells into Word as a table.

    wordsave gs table

    Alternatively, select Paste Special and select from the options that are provided.

    wordsave gs pastespecial

    You can’t use the Excel global objects from inside of Word without explicitly qualifying them (they simply don’t exist there). In particular, that means you can’t use Sheets. You should also explicitly declare the variable types of your parameters — otherwise they’ll be treated as Variant. This is important with reference types because in that it helps prevent run-time errors because the compiler knows that the Set keyword is required.

    Sub divider(wb1 As Object, dt1 As Document)
        Set dt1 = ThisDocument
        If dt1.Paragraphs.Count > 65000 Then
            Set cutrange = dt1.Range(dt1.Paragraphs(1).Range.Start, dt1.Paragraphs(65000).Range.End)
            If wb1.Sheets(wb1.Sheets.Count).Cells(1, 1) <> "" Then
                wb1.Sheets.Add After:=wb1.Sheets.Count
            End If
        Else
            Set cutrange = dt1.Content
            If wb1.Sheets(wb1.Sheets.Count).Cells(1, 1) <> "" Then
                wb1.Sheets.Add After:=wb1.Sheets.Count
            End If
        End If
        cutrange.Cut Destination:=wb1.Sheets(wb1.Sheets(wb1.Sheets.Count)).Cells(1, 1)
        wb1.Sheets(wb1.Sheets.Count).Cells(1, 1).TextToColumns Destination:=wb1.Sheets(1).Cells(1, 1)
    End Sub
    

    Note — you also don’t need to pass dt1 at all. You never use the value in the parameter and actually set it to something else. This could be a source of errors if you’re using internal calls, because dt1 is implicitly passed ByRef (it gets boxed when you call it through Application.Run). That means whenever you call divider, whatever you pass to dt1 in the calling code will change to ThisDocument. You should either remove the parameter or specify that it is ByVal.

    Хитрости »

    24 Февраль 2012              91368 просмотров


    Иногда бывает необходимо перенести что-то из Excel в другое приложение. Я возьму для примера Word. Например скопировать ячейки и вставить. Обычно мы это так и делаем — скопировали в Excel, открыли Word — вставили. Но сделать это при помощи кода чуть сложнее, хотя если разобраться никаких сложностей нет. Ниже приведен пример кода, который открывает Word, открывает в нем определенный документ, копирует данные из Excel и вставляет в открытый документ Word.

    Sub OpenWord()
        Dim objWrdApp As Object, objWrdDoc As Object
        'создаем новое приложение Word
        Set objWrdApp = CreateObject("Word.Application")
        'Можно так же сделать приложение Word видимым. По умолчанию открывается в скрытом режиме
        'objWrdApp.Visible = True
        'открываем документ Word - документ "Doc1.doc" должен существовать
        Set objWrdDoc = objWrdApp.Documents.Open("C:Doc1.doc")
        'Копируем из Excel диапазон "A1:A10"
        Range("A1:A10").Copy
        'вставляем скопированные ячейки в Word - в начала документа
        objWrdDoc.Range(0).Paste
        'закрываем документ Word с сохранением
        objWrdDoc.Close True    ' False - без сохранения
        'закрываем приложение Word - обязательно!
        objWrdApp.Quit
        'очищаем переменные Word - обязательно!
        Set objWrdDoc = Nothing: Set objWrdApp = Nothing
    End Sub

    Скачать пример:

      Tips_Macro_OpenWord.xls (49,5 KiB, 6 261 скачиваний)

    В файле-примере, приложенном к данной статье, в комментариях к коду есть несколько добавлений. Например, как вставить текст из ячеек в определенные закладки Word-а и как добавить новый документ, а не открывать уже имеющийся. Так же так есть код проверки — открыто ли приложение Word в данный момент. Порой это тоже может пригодиться, чтобы работать с запущенным приложением Word, а не создавать новое:

    Sub Check_OpenWord()
        Dim objWrdApp As Object
        On Error Resume Next
        'пытаемся подключится к объекту Word
        Set objWrdApp = GetObject(, "Word.Application")
        If objWrdApp Is Nothing Then
            'если приложение закрыто - создаем новый экземпляр
            Set objWrdApp = CreateObject("Word.Application")
            'делаем приложение видимым. По умолчанию открывается в скрытом режиме
            objWrdApp.Visible = True
        Else
            'приложение открыто - выдаем сообщение
            MsgBox "Приложение Word уже открыто", vbInformation, "Check_OpenWord"
        End If
    End Sub

    В принципе, активировать или вызвать(если закрыто) другое приложение Офиса можно одной строкой:

    Sub Open_AnotherApp()
        Application.ActivateMicrosoftApp xlMicrosoftWord
    End Sub

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

    По сути, методами CreateObject и GetObject можно обратиться к любому стороннему приложению(например Internet Explorer). Куда важнее при обращении к этим объектам знать объектную модель того приложения, к которому обращаетесь. Чтобы увидеть свойства и методы объектной модели приложения, можно в редакторе VBA подключить необходимую библиотеку, объявить переменную, назначив ей тип приложения. Покажу на примере того же Word-а.
    Для начала открываем меню Tools -References:

    Подключаем библиотеку:

    Затем объявляем переменную и присваиваем ей тип нужного приложения:

    Sub OpenWord()
        Dim objWrdApp As Word.Application
        Set objWrdApp = New Word.Application
        objWrdApp.Visible = True
    End Sub

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

    Так же можно нажать F2 и через поиск найти Word и просмотреть все методы и свойства данного приложения.

    Метод установки ссылки на библиотеку приложения через ToolsReferences называют еще ранним связыванием. Подобный метод позволяет создать ссылку на приложение быстрее и, как описано выше, предоставляет разработчику доступ к визуальному отображению свойств и методов объекта. Но есть существенный минус: если в своем коде Вы установите ссылку на Word 12 Object Libbary(Word 2007), то на ПК с установленным Word 2003 получите ошибку MISSING, т.к. Word 2003 относится к библиотеке Word 11 Object Libbary. Подробнее можно прочитать в статье Ошибка — Cant find project or library.
    Метод же CreateObject еще называется методом позднего связывания. Применяя его не возникнет проблем с MISSING, очень часто возникающих при раннем связывании. Поэтому я рекомендовал бы при разработке использовать раннее связывание для удобства использования свойств и методов(если Вы их не знаете), а перед распространением приложения в коде заменить все именованные константы(типа wdLine) на числовые константы(для wdLine это 5) и применить позднее связывание. Посмотреть числовое значение константы можно просто записав её в коде, начать выполнение кода через F8 и навести курсор мыши на эту константу. Всплывающая подсказка покажет числовое значение. Так же можно отобразить окно Immediate(ViewImmediate Window или сочетание клавиш Ctrl+G), записать вопросительный знак и вставить эту константу и нажать Enter:
    ?wdLine
    ниже будет выведено числовое представление этой константы.
    А заменять эти константы их числовыми значениями в случае с поздним связыванием необходимо, т.к. Excel не знает их значений.
    Попробую пояснить поподробнее про эти константы и почему их надо заменять какими-то числами: при подключении библиотеки Wordа(Word 12 Object Libbary) мы так же подключаем и все свойства, методы и константы, которые доступны из Wordа. И их использование напрямую становится доступно из Excel и мы можем смело написать что-то вроде wbLine и Excel поймет эту константу. При позднем же связывании мы уже не подключаем библиотеки Word(во избежание ошибок совместимости) и как следствие — методы, свойства и константы Wordа для Excel становятся чем-то неизвестным и не документированным и мы получим ошибку «Variable not defined»(если включена директива Option Explicit) при попытке назначить свойство через wdLine. Если же Option Explicit не включена — то хоть ошибки не будет, но и код будет работать неверно, т.к. для неизвестной для Excel переменной wbLine будет назначено значение 0(Empty). Поэтому и надо все константы другого приложения заменять их числовыми значениями.

    Главная ошибка новичка
    И хочу так же упомянуть про ошибку, которую очень часто совершают при обращении к одному приложению из другого. Допустим, необходимо скопировать из Word все данные в Excel. Часто начинающие делают это так:

    Sub OpenWord()
        Dim objWrdApp As Object, objWrdDoc As Object
        'создаем новое приложение Word
        Set objWrdApp = CreateObject("Word.Application")
        'Можно так же сделать приложение Word видимым. По умолчанию открывается в скрытом режиме
        'objWrdApp.Visible = True
        'открываем документ Word - документ "Doc1.doc" должен существовать
        Set objWrdDoc = objWrdApp.Documents.Open("C:Doc1.doc")
        'Копируем из Word все данные, обращаясь к объекту Range документа
        Range.Copy
        'вставляем скопированное в ячейку А1 активного листа Excel
        ActiveSheet.Paste
        'закрываем документ Word без сохранения
        objWrdDoc.Close False
        'закрываем приложение Word
        objWrdApp.Quit
        'очищаем переменные Word - обязательно!
        Set objWrdDoc = Nothing: Set objWrdApp = Nothing
    End Sub

    На строке Range.Copy обязательно получите ошибку от VBA, указывающую, что нужен аргумент для объекта. Можно попробовать добавить этот аргумент: Range(1).Copy. Но все равно получим ошибку. Можно, конечно, указать даже ячейки: Range(«A1»).Copy. Но это приведет к тому, что скопирована будет ячейка А1 активного листа Excel.
    Все дело в том, что мы хотим скопировать данные из Word-а, выполняя при этом код из Excel. А у Excel тоже есть объект Range с другими аргументами. И если не указать какому приложению, листу или документу принадлежит Range, то по умолчанию он будет отнесен к тому приложению, из которого выполняется код. Т.е. к Excel. Если совсем кратко об этом — всегда надо указывать какому приложению или объекту принадлежит используемый объект или свойство. Правильно код должен выглядеть так:

    Sub OpenWord()
        Dim objWrdApp As Object, objWrdDoc As Object
        'создаем новое приложение Word
        Set objWrdApp = CreateObject("Word.Application")
        'Можно так же сделать приложение Word видимым. По умолчанию открывается в скрытом режиме
        'objWrdApp.Visible = True
        'открываем документ Word - документ "Doc1.doc" должен существовать
        Set objWrdDoc = objWrdApp.Documents.Open("C:Doc1.doc")
        'Копируем из Word все данные, обращаясь к объекту Range документа
        'при этом перед Range явно указываем откуда его брать - из документа Word -objWrdDoc("C:Doc1.doc")
        objWrdDoc.Range.Copy
        'вставляем скопированное из Word в активную ячейку активного листа Excel
        ActiveSheet.Paste
        'закрываем документ Word без сохранения
        objWrdDoc.Close False
        'закрываем приложение Word
        objWrdApp.Quit
        'очищаем переменные Word - обязательно!
        Set objWrdDoc = Nothing: Set objWrdApp = Nothing
    End Sub

    Вместо Range ту же ошибку делают и с Selection(потому что Selection часто присутствует в записанных макрорекордером макросах), т.к. этот объект есть и в Excel и в Word и без явного указания приложения будет относится к приложению, в котором записано.


    В приложенном файле код немного отличается от представленных выше — в нем можно посмотреть как вставить текст из ячеек в определенные(созданные заранее) закладки Word-а. Это удобно для создания бланков в Word и заполнения их через Excel

    Скачать пример:

      Tips_Macro_OpenWord.xls (49,5 KiB, 6 261 скачиваний)


    А в архиве ниже — практически готовое решение заполнения всевозможных бланков Word из Excel. Как это работает. У нас есть таблица Excel с данными для заполнения бланков заявлений на пособия:
    Исходная таблица
    Обращаю внимание, что в первой строке расположены метки. Они нужны для того, чтобы код мог понять значения какого столбца в какое место шаблона Word должны попасть. А в самом шаблоне Word мы должны проставить эти самые метки:
    Шаблон Word с метками
    Фигурные скобки сделаны для того, чтобы код 100% искал и заменял только метку в шаблоне, исключая при этом замену случайного текста вне скобок(ведь слово «Должность» может встречаться и само по себе).
    А здесь я схематично привел то, как будут происходить замены:
    Схема замен
    Сначала программа создаст новую папку, в которую и будет сохранять создаваемые файлы(имя папки состоит из даты и времени запуска кода). Далее программа циклом пройдется по каждой строке таблицы, создаст на основании шаблона Word(«Шаблон.doc») новый файл для этой строки, заполнит этот шаблона данными на основании меток, и сохранит созданный файл под новым именем. Сам файл шаблона при этом не изменяется — все метки в нем сохраняются как были настроены до запуска кода. Конкретно в приложенном коде значение для имени нового файла берется из первого столбца «ФИО с инициалами». Но это можно изменить в коде при необходимости. Делается это в этой строке:

    'считываем фамилию с инициалами
    sWDDocName = .Cells(lr, 1).Value

    Что еще важно: файл шаблона Word должен находиться в той же папке, что и файл с кодом. Название файла в приложенном к статье файле должно быть «Шаблон.doc». Но его так же можно изменить, не забыв изменив его в коде в этой строке:

    'имя шаблона Word с основным текстом и метками
    Const sWDTmpl As String = "Шаблон.doc"

    В общем-то, если хоть чуть-чуть разбираетесь, то поменять можно многое. А для тех, кто не разбирается достаточно будет просто создавать метки в файле Word и обозначать ими столбца в таблице Excel. Количество столбцов и строк в таблице код определяет автоматически и при изменении размеров таблицы ничего изменять не надо. Главное, чтобы метки находились в первой строке, вторая строка — заголовок(необязательно), а с третьей строки начинаются данные, которые и используются для наполнения шаблонов.
    Скачать пример:

      Автосоздание бланков Word из таблицы Excel.zip (37,6 KiB, 1 468 скачиваний)

    Примеры работы с тем же Outlook можно посмотреть в моих статьях:
    Как отправить письмо из Excel?
    Сохранить вложения из Outlook в указанную папку


    Статья помогла? Поделись ссылкой с друзьями!

      Плейлист   Видеоуроки


    Поиск по меткам

    

    Access
    apple watch
    Multex
    Power Query и Power BI
    VBA управление кодами
    Бесплатные надстройки
    Дата и время
    Записки
    ИП
    Надстройки
    Печать
    Политика Конфиденциальности
    Почта
    Программы
    Работа с приложениями
    Разработка приложений
    Росстат
    Тренинги и вебинары
    Финансовые
    Форматирование
    Функции Excel
    акции MulTEx
    ссылки
    статистика

    INTELLIGENT WORK FORUMS
    FOR COMPUTER PROFESSIONALS

    Contact US

    Thanks. We have received your request and will respond promptly.

    Log In

    Come Join Us!

    Are you a
    Computer / IT professional?
    Join Tek-Tips Forums!

    • Talk With Other Members
    • Be Notified Of Responses
      To Your Posts
    • Keyword Search
    • One-Click Access To Your
      Favorite Forums
    • Automated Signatures
      On Your Posts
    • Best Of All, It’s Free!

    *Tek-Tips’s functionality depends on members receiving e-mail. By joining you are opting in to receive e-mail.

    Posting Guidelines

    Promoting, selling, recruiting, coursework and thesis posting is forbidden.

    Students Click Here

    How do I call a word macro from excel?

    How do I call a word macro from excel?

    (OP)

    18 Dec 03 11:49

    How do I call a word macro from excel?

    thanks,
    chris

    Red Flag Submitted

    Thank you for helping keep Tek-Tips Forums free from inappropriate posts.
    The Tek-Tips staff will check this out and take appropriate action.

    Join Tek-Tips® Today!

    Join your peers on the Internet’s largest technical computer professional community.
    It’s easy to join and it’s free.

    Here’s Why Members Love Tek-Tips Forums:

    • Tek-Tips ForumsTalk To Other Members
    • Notification Of Responses To Questions
    • Favorite Forums One Click Access
    • Keyword Search Of All Posts, And More…

    Register now while it’s still free!

    Already a member? Close this window and log in.

    Join Us             Close

    1. 03-19-2009, 03:58 PM


      #1

      gnome_core is offline


      Registered User


      Calling word from excel

      Hello,

      The code below basically copies files with an .mht extension to a temp directory then opens those files from the temp directory in word and saves them as a .html extension. I have all my references set and this process works fine until it gets about half way through the save as .html process. There error message I get is vaugue: «Error 91: Object variable or With Block variable not set». Does anyone see anything incorrect with my code? Since this process works up until some point, I can’t determine what the issue is.


    2. 03-19-2009, 04:07 PM


      #2

      Re: Calling word from excel

      Entia non sunt multiplicanda sine necessitate


    3. 03-19-2009, 04:12 PM


      #3

      Re: Calling word from excel

      Hello gnome_core,

      You didn’t use the Set statement to free the objects you declared.

      It should be this…

      Sincerely,
      Leith Ross

      Remember To Do the Following….

      1. Use code tags. Place [CODE] before the first line of code and [/CODE] after the last line of code.

      2. Thank those who have helped you by clicking the Star below the post.

      3. Please mark your post [SOLVED] if it has been answered satisfactorily.

      Old Scottish Proverb…
      Luathaid gu deanamh maille! (Rushing causes delays!)


    4. 03-19-2009, 04:25 PM


      #4

      Re: Calling word from excel

      Aside from that (and there’s no need to do it; they are set to Nothing when they go out of scope), you mifght want to make sure you’re not trying to loop through an empty collection:

      Last edited by shg; 03-19-2009 at 04:28 PM.


    5. 03-19-2009, 04:44 PM


      #5

      Re: Calling word from excel

      Hello Shg,

      When objects are late bound, the memory allocated to the object is not released automatically when it goes out of scope. There are a few exceptions to the rule, like the Dictionary object.

      Error 91 is generated by attempting to assign an object without using the Set statement. So removing the statements will stop the error, but does not address the cause.


    6. 03-19-2009, 04:54 PM


      #6

      Re: Calling word from excel

      I changed them to early bound.


    7. 03-20-2009, 11:19 AM


      #7

      gnome_core is offline


      Registered User


      Re: Calling word from excel

      Thank you both. That has resolved that issue. However, a new one is happening. The error message is: «Error 5180: Method ‘open’ of object ‘Documents’ failed. This occurs on the line:

      And it always happens on the 60th file to open. So everything works as intended until it gets to the 60th file to open. I verified it is not the actual file as I’ve tried this with may different files in the folder. Is there some restriction on the number of word docs you can cycle through in a procedure? Really doesn’t make much sense to me.

      Thanks again,
      J


    8. 03-20-2009, 11:36 AM


      #8

      Re: Calling word from excel


    9. 03-20-2009, 12:53 PM


      #9

      gnome_core is offline


      Registered User


      [Solved] Re: Calling word from excel

      Once I set this:

      everything worked. I was able to process all 170 files in the dir.

      I updated my code to use this new logic:

      Thanks for all the help!

      Last edited by gnome_core; 03-20-2009 at 01:13 PM.


    10. 03-20-2009, 12:57 PM


      #10

      Re: Calling word from excel

      Glad you got it sorted out, and thanks for posting back with the solution. I don’t do any Word automation, and so couldn’t contribute much.

      Would you please mark the thread as Solved?

      Click the Edit button on your first post in the thread

      Click Go Advanced, select [SOLVED] from the Prefix dropdown, then click Save Changes


    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:

    Понравилась статья? Поделить с друзьями:
  • Call vba excel описание
  • Call symbol in word
  • Call out text in word
  • Call out one word or two
  • Call of duty world at word