Word:用于在表列中设置书签的宏,没有第一行



我正在使用Microsoft Word中的宏。 我需要引用列中的整个单元格范围,除了第一行或"标题"。

我的最终目标只是创建VBA代码,该代码可以剪切D列中的所有值并将它们粘贴到A列中。

我依靠书签来做到这一点。我有一个创建表的宏,然后我想插入类似以下内容的内容:

ActiveDocument.Bookmarks.Add _
  Name:="ProposedMedTargets", Range:=Selection.Tables(1).Columns(6)

但是我需要这个书签来排除第一行。 单元格区域不是静态的,因为用户可以随时向表中添加新行。 我确实尝试在网上找到这个,但无法遇到这个特定的用例。

这是一个简短的方法。

    Selection.SetRange ActiveDocument.Tables(1).rows(2).Cells(2).Range.Start, _
           ActiveDocument.Tables(1).rows.Last.Cells(2).Range.End
    ActiveDocument.Bookmarks.Add "ProposedMedTargets", Selection.Range

(呵呵,我敢打赌不可能在 Word 中为列添加书签 - 怎么样......

这可以通过选择第二行中的单元格,然后按所需行数的计数向下扩展所选内容来完成。下面的示例代码在所选内容所在的列中设置书签。

Sub SetBookmarkForColumn()
    Dim sel As Word.Selection
    Dim nrRows As Long
    Set sel = Selection
    If sel.Information(wdWithInTable) Then
        nrRows = sel.Tables(1).Rows.Count
        sel.Columns(1).Cells(2).Select
        sel.MoveDown Count:=nrRows - 2, Extend:=True
        sel.Document.Bookmarks.Add "ProposedMedTargets", sel.Range
    End If
End Sub

尝试:

Dim r As Long, Rng As Range
Set Rng = Selection.Range
With ActiveDocument
  With .Tables(1)
    r = .Rows.Count - 2
    .Cell(2, 6).Range.Select
  End With
  Selection.MoveDown Count:=r, Extend:=True
  .Bookmarks.Add Name:="ProposedMedTargets", Range:=Selection
End With
Rng.Select
Set Rng = Nothing

最新更新