如何在 MS Word VBA 中获取当前表格? [英] How can you get the current table in MS Word VBA?

查看:136
本文介绍了如何在 MS Word VBA 中获取当前表格?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望能够运行一个 VBA 模块来操作我当前所在的表(即,光标位于该表中的某个位置).当您运行它时,VBA 代码将对您所在的每个表执行相同的操作.

I wish to be able to run a VBA module which manipulates the table that I'm currently in (i.e., the cursor is somewhere within that table). The VBA code will perform an identical operation on each table that you're in when you run it.

例如,假设我有一个模块需要将每个表格的顶行(标题)加粗.它需要定位您当前所在的表对象(称为 whatever),以便它可以操作 whatever.rows(0).

So, for example, let's say I have a module which needed to bold the top row of each table (the headings). It would need to locate the table object (called whatever) that you're currently in so that it could manipulate whatever.rows(0).

如何从光标位置获取表格对象?我还需要检测我是否不在在表中并且什么都不做(或引发错误对话框).

How can I get the table object from the cursor position? I also need to detect if I'm not in a table and do nothing (or raise an error dialog).

推荐答案

此答案底部的 VBA 子例程显示了如何执行此操作.

The VBA subroutine at the bottom of this answer shows how to do this.

使用当前选择,先折叠到起点,不用担心多段选择:

It uses the current selection, collapsing it to the starting point first so as to not have to worry about multi-segment selections:

Selection.Collapse Direction:=wdCollapseStart

然后检查该选择以确保它在表格内

It then checks that selection to ensure it's inside a table

    If Not Selection.Information(wdWithInTable) Then
        MsgBox "Can only run this within a table"
        Exit Sub
    End If

然后可以通过引用 Selection.Tables(1) 来访问该表.

The table is then accessible by referring to Selection.Tables(1).

下面的代码是一个简单的概念证明,它简单地切换表格每一行中的每个起始单元格以插入或删除垂直条标记.

The code below was a simple proof of concept which simply toggled each of the starting cells in each row of the table to either insert or delete a vertical bar marker.

Sub VertBar()
    ' Collapse the range to start so as to not have to deal with '
    ' multi-segment ranges. Then check to make sure cursor is '
    ' within a table. '
    Selection.Collapse Direction:=wdCollapseStart
    If Not Selection.Information(wdWithInTable) Then
        MsgBox "Can only run this within a table"
        Exit Sub
    End If

    ' Process every row in the current table. '
    Dim row As Integer
    Dim rng As Range

    For row = 1 To Selection.Tables(1).Rows.Count
        ' Get the range for the leftmost cell. '
        Set rng = Selection.Tables(1).Rows(row).Cells(1).Range

        ' For each, toggle text in leftmost cell. '
        If Left(rng.Text, 2) = "| " Then
            ' Change range to first two characters and delete them. '
            rng.Collapse Direction:=wdCollapseStart
            rng.MoveEnd Unit:=wdCharacter, Count:=2
            rng.Delete
        Else
            ' Just insert the vertical bar. '
            rng.InsertBefore ("| ")
        End If
    Next
End Sub

这篇关于如何在 MS Word VBA 中获取当前表格?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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