使用VBA / Macro将Word表格中的某些单元格对齐到右侧

时间:2013-05-29 16:18:06

标签: vba ms-word word-vba

VBA非常新,但我们的客户希望将1,850页Word表格中的所有数据对齐。我认为在VBA中这很容易。我想弄清楚,我确信我可以自己解决它,但截止日期迫使我寻求帮助。如果我错过了已发布的解决方案,我会提前道歉。

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

enter image description here

要成为这样:

enter image description here

所以我得到了:

 Dim oTable As Table
    Dim oRow As Row

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

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

1 个答案:

答案 0 :(得分:4)

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

这将帮助你完成大部分工作。

您目前没有提供足够的信息来保证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