Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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
like image 338
Vincent M Avatar asked Apr 21 '16 19:04

Vincent M


1 Answers

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"
like image 75
Cindy Meister Avatar answered Sep 28 '22 02:09

Cindy Meister