我想抓住一个运行的单词应用程序并插入一些文本。
VBA /宏代码从另一个单独的Microsoft应用程序(如Word或Excel)运行。这可能吗?
答案 0 :(得分:0)
这很容易。您只需要这个简单的代码就可以放入任何Excel,PP,Outlook模块。要从Word中捕获Word ......你不需要它,你只是在。
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
编辑如果您知道已打开的文档的名称,您可以通过这种方式捕获它并将一些文本放入其中:
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
答案 1 :(得分:0)
谢谢KazJaw。 但是,我想在打开的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