2013-02-21 565 views
2

我试图从Excel中访问MS Word的窗口。我找到了访问新的Word文档或特定文档的方法,如 Copy Text from Range in Excel into Word Document,使用VBA从Excel激活Word窗口

但在我的情况下,我不知道文档的名称,它应该是最后一个活动的文档。我希望能用

Word.ActiveDocument 

但没有成功。我也尝试模拟Alt + Tab键盘按键来激活窗口,使用

Application.SendKeys("%{TAB}") 

但它不起作用。任何提示?

我正在尝试创建一个宏,它将复制图表和一些文字到Word中,并对文本进行一些格式化处理。所以基本上我可以使用任何方法来完成这项任务。 非常感谢。

+1

[this](http://www.ehow.com/how_7355054_do-control-word-excel-vba_.html)可以帮助您更好地理解如何设置对象来控制excel中的单词vba(4-6) – scott 2013-02-21 15:22:02

+0

是否希望实际使用上一个活动文档,或者是否可以创建新文档? – Thomas 2013-02-21 16:04:31

+0

最后一份文件来自哪里?你在Excel或其他地方运行过代码吗? – Fionnuala 2013-02-21 16:23:22

回答

3

您可以通过使用后期绑定(http://support.microsoft.com/kb/245115)和GetObject来访问Word的打开实例。如果您有多个Word实例打开,您不能保证特别获取它们中的任何一个。

获取Word的实例将允许您访问ActiveDocument或应用程序的当前Selection。我仍然建议做一些错误检查,以确保你有你想要的。

Sub GetWordDocument() 
     Dim wdApp As Object 

     'Turn off error handling since if the Application is not found we'll get an error 
     'Use Late Binding and the GetObject method to find any open instances of Word 
     On Error Resume Next 
     Set wdApp = GetObject(, "Word.Application") 
     On Error GoTo 0 

     'Check to see if we found an instance. If not you can create one if you desire 
     If wdApp Is Nothing Then 
      MsgBox "No instances of Word found" 
      Exit Sub 
     End If 

     'Check if there are documents in the found instance of Word 
     If wdApp.Documents.Count > 0 Then 
      wdApp.Selection.TypeText "Cool, we got it" & vbCr 

      'You can now access any of the active document properties too 
      wdApp.ActiveDocument.Range.InsertAfter "We did indeed" 
     End If 

     'Clean up the Object when Finished 
     Set wdApp = Nothing 
    End Sub 
+0

正是我所需要的,非常感谢@CuberChase( - : – Pepacz 2013-02-25 10:31:18

+0

非常感谢,祝你好运! – CuberChase 2013-02-25 10:51:43