使用 VBA/宏将 Word 表格中的某些单元格向右对齐

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16819106/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-11 21:20:21  来源:igfitidea点击:

Align certain cells in Word table to the right with VBA/Macro

vbams-wordword-vba

提问by Tim Gottgetreu

very new to VBA but our clients want the all the data in 1,850 pages of Word Tables aligned right. I'm thinking this is pretty easy in VBA. I am trying to figure it out and I'm sure I could nail it on my own, but a deadline is forcing me to seek help. So I apologize in advance if I missed a published solution.

VBA 非常新,但我们的客户希望 1,850 页的 Word 表格中的所有数据都正确对齐。我认为这在 VBA 中很容易。我正在努力解决这个问题,而且我确信我可以自己解决,但截止日期迫使我寻求帮助。因此,如果我错过了已发布的解决方案,我提前道歉。

As an example they want this:

作为一个例子,他们想要这个:

enter image description here

在此处输入图片说明

To be this:

要这样:

enter image description here

在此处输入图片说明

So i've got:

所以我有:

 Dim oTable As Table
    Dim oRow As Row

    For Each oTable In ActiveDocument.Tables
     For Each oRow In oTable.Rows

But I don't know how to loop through just the body of the table. Also the top 4 rows (table title) is merged to one cell and the first column is still left aligned. Help, and the next rounds on me :)

但我不知道如何循环遍历表的主体。此外,前 4 行(表格标题)合并到一个单元格,第一列仍左对齐。帮助,和我的下一轮:)

回答by enderland

Normally I'm not a huge fan of "please write code for me" but I've not done enough with VBA in Word and want to learn some myself.

通常我不是“请为我编写代码”的忠实粉丝,但我对 Word 中的 VBA 做得不够,想自己学习一些。

This is going to get you most of the way there.

这将使您顺利完成大部分工作。

You do not currently provide enough information to allow me to guarantee the ifstatement is workable for the entiredocument but you should be able to go from here.

您目前没有提供足够的信息来让我保证该if声明适用于整个文档,但您应该可以从这里开始。



Sub alignTableElementsRight()
   Dim oTable As Table
   Dim oRow As Row

   Dim i As Integer
   Dim dataTable As Boolean

   For Each oTable In ActiveDocument.Tables
    'this will be set once you are in the "table" part and
    'not headings
    dataTable = False

    For Each oRow In oTable.Rows

       'you will need custom logic here to determine what your if statement
       'is to properly execute on the right row, this is going to depend based on your table
       'format, etc. This checks if a leftmost column heading is "65 to 66"
       If (InStr(oRow.Cells(1).Range.Text, "65 to 66") > 0) Then
         dataTable = True
       End If

       'if you are in the datatable, move all values to align right in each row following
       If (dataTable = True) Then
           For i = 2 To oRow.Cells.Count
               oRow.Cells(i).Range.ParagraphFormat.Alignment = wdAlignParagraphRight
           Next i
       End If


    Next oRow

   Next oTable
End Sub