'How to control one Word document from another Word document?
I am trying to use a master file, referred to as mDoc to copy charts from a slave file, called sDoc. It seems the code works during the first loop, but on the second and all subsequent loops, no charts are copied from the master to the slave.
Sub CopyAllCharts()
Dim objShape As InlineShape
Dim mDoc As Document
Dim sDoc As Document
Path = "C:\Users\ryans\Desktop\word_docs\"
File = Dir(Path & ".")
Do While File <> ""
Set mDoc = Documents("Testing.docm")
Set sDoc = Documents.Open(FileName:=Path & File)
Windows(sDoc).Activate
Debug.Print ActiveDocument.Name
For Each objShape In sDoc.InlineShapes
Debug.Print objShape.HasChart
If objShape.HasChart Then
objShape.Chart.Select
Selection.Copy
Windows(mDoc).Activate
Debug.Print ActiveDocument.Name
Selection.PasteAndFormat (wdPasteDefault)
Selection.Collapse Direction:=wdCollapseStart
End If
Next objShape
sDoc.Close SaveChanges:=False
File = Dir()
Loop
End Sub
During the first loop, these lines select and print the active document's name.
Windows(mDoc).Activate
Debug.Print ActiveDocument.Name
On the second and all other loops, Windows(mDoc).Activate does NOT activate the master document and Debug.Print ActiveDocument.Name prints the slave document's name but not the master document's name.
Solution 1:[1]
I tried to get the Range thing working, and made some progress, but in the end, I couldn't quite get it to work the way I wanted. Ultimately, I went with the code sample below, which does what I want.
Sub CopyAllCharts()
Dim objShape As InlineShape
Dim mDoc As Document
Dim sDoc As Document
Path = "C:\Users\ryans\Desktop\word_docs\"
File = Dir(Path & ".")
Do While File <> ""
Set mDoc = Documents("Control One Word Document From Another Word Document.docm")
Set sDoc = Documents.Open(FileName:=Path & File)
Windows(sDoc).Activate
If sDoc.Name = ActiveDocument.Name Then
Windows(sDoc).Activate
Debug.Print ActiveDocument.Name
For Each objShape In sDoc.InlineShapes
Debug.Print ActiveDocument.Name
Debug.Print objShape.HasChart
If objShape.HasChart Then
objShape.Chart.Select
Selection.Copy
If mDoc.Name <> ActiveDocument.Name Then
Windows(mDoc).Activate
End If
Debug.Print ActiveDocument.Name
Selection.PasteAndFormat (wdPasteDefault)
Selection.Collapse Direction:=wdCollapseStart
End If
Windows(sDoc).Activate
Debug.Print ActiveDocument.Name
Next objShape
End If
sDoc.Close SaveChanges:=False
File = Dir()
Loop
End Sub
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | ASH |
