2013-02-21 566 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