3

I'm fairly new to VBA, trying to fill out a word template from Excel with VBA in Excel. I'm using the following code to put in the Date into a tag in the word document: Dim Template As String

Dim WordDoc, WordApp As Object
Dim Template as String
On Error Resume Next                                                      
Set WordApp = GetObject("Word.Application")                                 
If Err.Number <> 0 Then                                                     
    Err.Clear                                                               
    Set WordApp = CreateObject("Word.Application")                          
    WordApp.Visible = True                                                  
End If
Template = "C:\Users\me\Dropbox\me - Summer 2019\RMA_Log\00059-001_E_24May19_Form Returned Authorization.docx"
Set WordDoc = WordApp.Documents.Open(FileName:=Template, ReadOnly:=False)
With WordDoc.Content.Find                                                   
    .Text = "<Date>"                                                        
    .Replacement.Text = "06-06-2019"                                        
    .Execute Replace:=wdReplaceAll, Forward:=True, Wrap:=wdFindContinue                                     
End With

But this won't replace any text in the main body of my word document.

I've tried doing WordDoc.ActiveDocument.Content.Find but that also doesn't work. If I copy the code exactly and replace WordDoc with ActiveDocument and run it in word VBA, the text gets replaced.

Dim Template As String
Template = "C:\Users\me\Dropbox\me - Summer 2019\RMA_Log\00059-001_E_24May19_Form Returned Authorization.docx"

With ActiveDocument.Content.Find                                                   
    .Text = "<Date>"                                                        
    .Replacement.Text = "06-06-2019"                                        
    .Execute Replace:=wdReplaceAll, Forward:=True, Wrap:=wdFindContinue                                     
End With

If I run this code in Word VBA, it replaces the Tag, why wouldn't it work to run this from Excel?

Edit: Office 2016

1 Answer 1

8

Excel doesn't know what wdReplaceAll or wdFindContinue are.

Put a reference to the Word Object Model (Tools > References > Microsoft Word XX Object Model).

And if you have Option Explicit at the top of your code it would highlight this.

Sign up to request clarification or add additional context in comments.

1 Comment

Works exactly how I expect it now, thank you very much!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.