宏将文本添加到Word表格中的选定范围

时间:2017-04-01 16:34:21

标签: vba excel-vba ms-word excel

我正在尝试编写一个宏,允许用户在Word表格中选择一系列单元格,以使用特定文本“已售出”填充第4列。

Word table

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

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。

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

1 个答案:

答案 0 :(得分:1)

这对我有用。而不是rng.text = ("SALE")使用:

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