【问题标题】:Adjusting the width of columns of all tables in a Word document调整Word文档中所有表格的列宽
【发布时间】:2023-04-08 03:16:01
【问题描述】:

在我的 Word 文档中,我有 300 多个表格,我想更改表格样式并调整列的宽度。我在我的 VBA 宏中使用以下代码。它适用于样式,但不适用于列宽。请帮我找出问题所在。

Sub Makro1()
'
' Makro1 Makro
'
'
    Selection.Find.ClearFormatting
    With Selection.Find
        .Text = "Variable"
        .Replacement.Text = ""
        .Forward = True
        .Wrap = wdFindContinue
        .Format = False
        .MatchCase = True
        .MatchWholeWord = False
        .MatchWildcards = False
        .MatchSoundsLike = False
        .MatchAllWordForms = False
    End With
    Selection.Find.Execute
    Selection.MoveRight Unit:=wdCharacter, Count:=1
    Selection.MoveRight Unit:=wdCharacter, Count:=4, Extend:=wdExtend
    Selection.Tables(1).Style = "eo_tabelle_2"
    With Tables(1).Spacing
     .Item(1) = 5.5 'adjusts width of text box 1 in cm
     .Item(2) = 8.5 'adjusts width of text box 2 in cm
     .Item(3) = 7.5 'adjusts width of text box 3 in cm
     .Item(4) = 1.1 'adjusts width of text box 4 in cm
End With
End Sub

【问题讨论】:

    标签: vba ms-word tabular


    【解决方案1】:

    我将按字面意思解释您的问题:您只想处理文档中的所有表格,并且您的代码仅使用 Find 来定位表格...

    以下示例展示了如何直接使用 Word 中的基础对象,而不是依赖当前的选择,这是宏记录器为您提供的。

    所以,一开始我们为 Document 和 Table 声明对象变量。具有焦点的当前文档被分配给第一个。然后,使用For Each...Next,我们可以遍历该文档中的每个 Table 对象并对每个对象执行相同的操作。

    在这种情况下,指定样式并设置列宽。请注意,为了给出以厘米为单位的列宽,必须使用内置转换函数CentimetersToPoints,因为 Word 以磅为单位测量列宽。

    Sub FormatTables
      Dim doc as Document
      Dim tbl as Table
    
      Set doc = ActiveDocument
      For Each tbl in doc.Tables
        tbl.Style = "eo_tabelle_2"
        tbl.Columns(1).Width = CentimetersToPoints(5.5)
        tbl.Columns(2).Width = CentimetersToPoints(8.5)
        tbl.Columns(3).Width = CentimetersToPoints(7.5)
        tbl.Columns(4).Width = CentimetersToPoints(1.1)
      Next
    End Sub
    

    【讨论】:

    • 您好,感谢您的帮助,但宽度命令似乎在没有列参数的情况下工作。但有参数它给出错误。
    • 我收到第 2,3 和第 4 列的错误 5941。你能帮我弄清楚为什么会这样...谢谢
    • @UsmanBhinder 错误的文本是什么?这个数字并没有告诉我任何事情......
    • @UsmanBhinder 我对代码做了一个小的更正,但它与列无关,就像你报告的那样。你的表有四列吗?
    【解决方案2】:

    据我所知,word 文件中的所有表都是Tables 集合的一部分,我们可以使用索引访问单个表项。假设您不知道表的数量,这里是适用于我的代码。

    For Each tbl In Doc.Tables
          tbl.Columns(3).Width = 40
    Next
    

    【讨论】:

    • 嗨,谢谢你的回答,但是 tbl.Columns(1).Width = CentimetersToPoints(5.5)
    • 哈哈,不错的观察伙伴。我只是错过了。我希望除了那个小失误之外,我能够帮助您解决您的问题。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-07-04
    • 2018-07-05
    • 2014-12-29
    • 1970-01-01
    • 1970-01-01
    • 2018-01-10
    相关资源
    最近更新 更多