繁体   English   中英

试图从另一个 Word 文档控制一个 Word 文档

[英]Trying to control one Word document from another Word document

我正在尝试使用称为 mDoc 的主文件从称为 sDoc 的从属文件复制图表。 看起来代码在第一个循环期间工作正常,但在第二个循环和所有后续循环中,没有图表可以从主机处理到从机。 这是我的代码。

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

这应该很接近,但是在第一个循环期间,有些东西是关闭的。 这些行 select 并打印活动文档的名称。

Windows(mDoc).Activate
Debug.Print ActiveDocument.Name

第二个循环和所有其他循环, Windows(mDoc).Activate不激活主文档, Debug.Print ActiveDocument.Name打印从属文档的名称,但不打印主文档的名称。 同样,这应该接近 wrking,但有些地方不太正确,比如某种 object 参考,或类似的东西。 有人可以帮我解决这个问题吗?

我试图让 Range 工作,并取得了一些进展,但最后,我无法让它按照我想要的方式工作。 最终,我使用了下面的代码示例,它可以满足我的需求。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM