【问题标题】:How do I insert text at my cursor location in Word?如何在 Word 中的光标位置插入文本?
【发布时间】:2016-04-25 23:52:01
【问题描述】:

我正在尝试让我的 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

【问题讨论】:

    标签: vba excel ms-word


    【解决方案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"
    

    【讨论】:

    • 如果选择为空,你插入一个字符串(我插入了一个日期字符串),你必须手动移动光标,如下:Selection.MoveRight unit:=wdCharacter, count:=Len(curdate)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-02-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-07
    • 2012-06-20
    相关资源
    最近更新 更多