excelor100
New Member
- Joined
- Aug 10, 2017
- Messages
- 8
Hi all
I'm trying to amend this macro so that rather than create a new word document from the path name, it instead just opens up the actual document in the path name and makes the changes.
I am happy with the path it currently uses (since it searches for the named doc within the code in the same path as the workbook) this is perfect for my needs. But I would much prefer that it opens the document in question and then does it work of inserting data into bookmarks.
Can anyone help? Having spent a few hours on it today I'm struggling to get it working. Any help appreciated!
I'm trying to amend this macro so that rather than create a new word document from the path name, it instead just opens up the actual document in the path name and makes the changes.
I am happy with the path it currently uses (since it searches for the named doc within the code in the same path as the workbook) this is perfect for my needs. But I would much prefer that it opens the document in question and then does it work of inserting data into bookmarks.
Can anyone help? Having spent a few hours on it today I'm struggling to get it working. Any help appreciated!
Code:
Option Explicit
Sub Reportcreatebutton2()
Dim pappWord As Object
Dim docWord As Object
Dim wb As Excel.Workbook
Dim xlName As Excel.Name
Dim TodayDate As String
Dim Path As String
Set wb = ActiveWorkbook
TodayDate = Format(Date, "mmmm d, yyyy")
Path = wb.Path & "\Test1.docm"
On Error GoTo ErrorHandler
'Create a new Word Session
Set pappWord = CreateObject("Word.Application")
On Error GoTo ErrorHandler
'Open document in word
Set docWord = pappWord.Documents.Add(Path)
'Loop through names in the activeworkbook
For Each xlName In wb.Names
'if xlName's name is existing in document then put the value in place of the bookmark
If docWord.Bookmarks.Exists(xlName.Name) Then
docWord.Bookmarks(xlName.Name).Range.Text = Range(xlName.Value).Text
End If
Next xlName
'Activate word and display document
With pappWord
.Visible = True
.ActiveWindow.WindowState = 0
.Activate
End With
'Release the Word object to save memory and exit macro
ErrorExit:
Set pappWord = Nothing
Exit Sub
'Error Handling routine
ErrorHandler:
If Err Then
MsgBox "Error No: " & Err.Number & "; There is a problem"
If Not pappWord Is Nothing Then
pappWord.Quit False
End If
Resume ErrorExit
End If
End Sub