2016-04-21 105 views
2

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

这是我写的。我知道ActiveDocument.Range具有开始和结束参数,但我似乎无法将它们的“当前选择”指定为值。帮帮我?谢谢?

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

当前选择是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" 
+0

谢谢辛迪!有用!我只修改了一个小工具,它的作用就是设置wdApp = GetObject(,“Word.Application”) 一行中的逗号和空格。 子Inserttext() 昏暗wdApp作为Word.Application 集wdApp = GetObject的( “Word.Application”) wdApp.Selection.Text = “文本在当前选择” “获取当前选择一个范围 昏暗的RNG作为Word.Range 设置RNG = wdApp.Selection.Range rng.Text =“这个文本将取代当前所选文本” rng.Collapse wdCollapseEnd rng.Text =“这个文本会后当前选择“ End Sub 再次感谢! –

+0

@VincentM很高兴帮助:-)感谢您指出错误:我在我的平板电脑上从内存中打字,并且不记得可选文件路径(用于拾取特定文件)是在之前还是之后应用程序标识... 我在我的“答复”中更正了它。 –

相关问题