简体   繁体   中英

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

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.

As an example they want this:

在此处输入图片说明

To be this:

在此处输入图片说明

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 :)

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.

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

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


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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM