读取当前选定的行

时间:2015-01-16 13:57:02

标签: vba ms-word

(这应该很简单,但不知怎的,我找不到解决方案。)

我只想将我选择的当前行读入vba中的变量。我不知道目前的段落。选择是在该行的最开始。

我的文档看起来像这样。

My Word doc

首先,我选择表格的第一行。然后我向上移动一段。现在就是我想要的那条线。正如你在我的第二个img中看到的,我只有第一个角色。

For Each tbl In fileInsertRange.Tables
    tbl.Rows(1).Select
    ' save caption
    Selection.Collapse
    Selection.MoveUp WdUnits.wdParagraph, 1

    tableCaption = Selection.Text

Debugging

1 个答案:

答案 0 :(得分:1)

如果要将所有表格标题存储在变量中,请尝试使用此代码。请记住,在被下一个表格标题覆盖之前,您需要立即使用tableCaption变量,或添加一个数组来存储所有标题。

Sub get_table_caption()

Dim currentTable As Table
Dim tableCaption As String

'Loop through all tables on active document
For Each currentTable In ActiveDocument.Tables

    'Get tables caption and store in a variable called "tableCaption"
    currentTable.Select
    Selection.Collapse
    Selection.MoveUp WdUnits.wdParagraph, 1
    Selection.Expand wdLine
    tableCaption = Selection.Text
    Debug.Print tableCaption

    'Do stuff with the tables caption

Next
End Sub

如果您想通过选择表格的第一行并找到表格标题而不是尝试此代码继续按照您的方式进行操作:

Sub get_table_caption()

Dim tableCaption As String

    'Get tables caption and store in a variable called "tableCaption"
    Selection.Collapse
    Selection.MoveUp WdUnits.wdParagraph, 1
    Selection.Expand wdLine
    tableCaption = Selection.Text
    Debug.Print tableCaption

End Sub

希望有所帮助。祝你好运。