简体   繁体   中英

Excel VBA not consistently formatting the table margins

I have an excel form that will open up ms word and go to the sixth table and adjust the cell margins. I want the left and right cell margins to be 0.08 for the entire table.

https://i.stack.imgur.com/VvYJY.jpg

It works perfectly the first time the form is run, but the second time and after it won't do it. Here is my code. Can anyone tell me why this would happen?

Public Sub Table()

    Dim wrdApp
    Dim wrdDoc
    Set wrdApp = CreateObject("Word.Application")
    wrdApp.Visible = False
    Set wrdDoc = wrdApp.Documents.Open("\\FileLocation")

    With wrdDoc
        'Goes to 6th table and selects it
        wrdApp.Selection.Goto wdGoToPage, wdGoToAbsolute, 1
        wrdApp.Selection.Goto What:=wdGoToTable, Which:=GoToNext
        wrdApp.Selection.Goto What:=wdGoToTable, Which:=GoToNext
        wrdApp.Selection.Goto What:=wdGoToTable, Which:=GoToNext
        wrdApp.Selection.Goto What:=wdGoToTable, Which:=GoToNext
        wrdApp.Selection.Goto What:=wdGoToTable, Which:=GoToNext
        wrdApp.Selection.Goto What:=wdGoToTable, Which:=GoToNext
        wrdApp.Selection.Tables(1).Select


        With wrdApp.Selection.Tables(1)
            .TopPadding = InchesToPoints(0)
            .BottomPadding = InchesToPoints(0)
            .LeftPadding = InchesToPoints(0.08)
            .RightPadding = InchesToPoints(0.08)
            .Spacing = 0
            .AllowPageBreaks = True
            .AllowAutoFit = True
        End With

End Sub

Why are you using wrdApp.Selection.Goto What:=wdGoToTable, Which:=GoToNext ? Why not Set wrdTbl = wrdDoc.Tables(6) and work with that? All that code may be referring to another table?

Try something like this:

Private Sub Sample()   
    Dim wrdApp As Object, wrdDoc As Object, wrdTbl As Object

    Set wrdApp = CreateObject("Word.Application")
    wrdApp.Visible = False

    Set wrdDoc = wrdApp.Documents.Open("\\FileLocation")

    Set wrdTbl = wrdDoc.Tables(6)

    With wrdTbl
        .TopPadding = wrdApp.InchesToPoints(0)
        .BottomPadding = wrdApp.InchesToPoints(0)
        .LeftPadding = wrdApp.InchesToPoints(0.08)
        .RightPadding = wrdApp.InchesToPoints(0.08)
        .Spacing = 0
        .AllowPageBreaks = True
        .AllowAutoFit = True
    End With    
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