0

我想获取一个正在运行的 word 应用程序并插入一些文本。

VBA/宏代码从另一个单独的 Microsoft 应用程序(例如 Word 或 Excel)运行。这可能吗?

4

2 回答 2

0

谢谢卡兹乔。但是,我想将文本添加到打开的 Word 文档中,而不是添加另一个。根据您的代码

Sub catch_word()
   Dim WRD As Object
   Dim WRD_WINDOWS As Object
   Dim strTemp As String

  On Error Resume Next
Set WRD = GetObject(, "Word.Application")

If WRD Is Nothing Then
    MsgBox "Word Application is not open"
Else

    Set WRD_WINDOWS = WRD.Windows

    For Each win In WRD_WINDOWS
        If (win.Document.FullName = "Document1") Then
            win.Document.Range(Start:=125, End:=134).Text = "Some Text"
            strTemp = win.Document.Range(Start:=5, End:=10).Text
        End If

    Next
End If
于 2013-05-24T20:39:01.467 回答
0

It is quite easy. You need just this simple code to put inside any Excel, PP, Outlook Module. To catch Word from Word... you don't need it, you are just in.

Sub catch_word()
    Dim WRD As Object

    On Error Resume Next
    Set WRD = GetObject(, "Word.Application")

    If WRD Is Nothing Then
        MsgBox "Word Application is not open"
    Else
        'add new document and add text into it
        Dim DOC
        Set DOC = WRD.documents.Add
        DOC.Content.Text = "First text into document"
    End If

End Sub

Edit If you know the name of the document which is already opened you could go this simply way to catch it and put some text into it:

Sub catch_word_document()
    Dim WRD As Object

    On Error Resume Next
    Set WRD = GetObject("Document1")

    If WRD Is Nothing Then
        MsgBox "Word Application is not open"
    Else
        'add text into it
        WRD.Content.Text = "First text into document"
    End If

End Sub
于 2013-05-24T05:49:45.043 回答