How do I insert text at my cursor location in Word?

北慕城南 提交于 2020-01-04 00:12:39

问题


I'm trying to have my Excel macro insert some text at my cursor location in a already-opened Word Document.

This is what I have written. I'm aware that the ActiveDocument.Range has the Start and End arguments, but I cannot seem to be able to assign them the "current selection" as a value. Help? Thanks?

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:


The current selection is Selection.

If, as you indicate, you need to use this in an Excel macro that's automating Word, then you need to use the Word.Application object you've declared and instantiated to qualify it. It would look something like this:

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"


来源:https://stackoverflow.com/questions/36778442/how-do-i-insert-text-at-my-cursor-location-in-word

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!