如何在Word中的光标位置插入文本?

时间:2016-04-21 19:09:29

标签: vba excel-vba word-vba excel

我试图让我的Excel宏在我已经打开的Word文档中的光标位置插入一些文本。

这就是我写的。我知道ActiveDocument.Range有Start和End参数,但我似乎无法为它们分配"当前选择"作为一种价值。救命?感谢?

Sub InsertText()

Dim rngTemp As Word.Range

Set rngTemp = ActiveDocument.Range

With rngTemp

    .InsertAfter "This is my sample text"
    .Font.Name = "Tahoma"
    .Font.Size = 11
    .InsertParagraphAfter
End With

End Sub

1 个答案:

答案 0 :(得分:2)

当前选择为Selection

如果,如您所示,您需要在自动运行Word的Excel宏中使用它,那么您需要使用已声明并实例化的Word.Application对象来限定它。它看起来像这样:

Dim wdApp as Word.Application
Set wdApp = GetObject(, "Word.Application")
wdApp.Selection.Text = "text at the current selection"
'Get a Range for the current selection
Dim rng as Word.Range
Set rng = wdApp.Selection.Range
rng.Text = "this text will replace the text in the current selection"
rng.Collapse wdCollapseEnd
rng.Text = " and this text will come after the current selection"