将文本添加到Word表中所选范围的宏 [英] Macro to add text to a selected range in a Word Table

查看:224
本文介绍了将文本添加到Word表中所选范围的宏的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写一个宏,允许用户在Word表格中选择一系列单元格,以填充具有特定文本SOLD的列4。

I am trying to write a Macro that allows the user to select a range of cells in a Word Table to populate Column 4 with a specific text "SOLD".

以下是我到目前为止的VBA宏代码,但它只会在第一列第4列中输入文本(而不是第4列的选定范围)

Below is my VBA Macro code so far, but it only types the text in the first Column 4 (rather than the selected range of column 4's)

Dim iSelectionRowEnd As Integer
Dim iSelectionRowStart As Integer
Dim cl1 As Cell
Dim cl2 As Cell
Dim tbl As Table
Dim rng As Range

ActiveDocument.Bookmarks.Add Name:="MacroStartPosition", Range:=Selection.Range

If Selection.Information(wdWithInTable) = False Then
    MsgBox "Selection is not in a table."
Else

    iSelectionRowEnd = Selection.Information(wdEndOfRangeRowNumber)
    Selection.Collapse Direction:=wdCollapseStart


    iSelectionRowStart = Selection.Information(wdEndOfRangeRowNumber)

    Set tbl = Selection.Tables(1)
    Set cl1 = tbl.Cell(iSelectionRowStart, 4)
    Set cl2 = tbl.Cell(iSelectionRowEnd, 4)
    Set rng = cl1.Range.Duplicate
    rng.End = cl2.Range.End
    rng.text = ("SALE")

End If
Selection.Collapse Direction:=wdCollapseStart

If ActiveDocument.Bookmarks.Exists("MacroStartPosition") = True Then
    ActiveDocument.Bookmarks("MacroStartPosition").Select
    ActiveDocument.Bookmarks("MacroStartPosition").Delete
Else
    MsgBox "The original cursor position could not be restored."
End If

Selection.Collapse Direction:=wdCollapseStart

我试图在Excel中遵循类似的代码并将其应用于Word,但是我收到错误。参见下面的Excel。

I tried to follow a similar code in Excel and apply it to Word, but I am getting errors. See below Excel.

ActiveCell.FormulaR1C1 = "SALE"
Selection.AutoFill Destination:=Range("D3:D7"), Type:=xlFillDefault
Range("D3:D7").Select


推荐答案

这对我有用。使用

For i = iSelectionRowStart To iSelectionRowEnd
    tbl.Cell(i, 4).Range.Text = "SALE"
Next

这篇关于将文本添加到Word表中所选范围的宏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆