Excel VBA不一致地格式化表格边距

时间:2018-10-01 15:33:11

标签: excel vba excel-vba ms-word

我有一个excel表格,它将打开ms word并转到第六张表并调整单元格边距。我希望整个表格的左右单元格边距为0.08。

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

第一次运行该表单时效果很好,但是第二次及其后将无法运行。这是我的代码。谁能告诉我为什么会这样?

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

1 个答案:

答案 0 :(得分:2)

您为什么要使用wrdApp.Selection.Goto What:=wdGoToTable, Which:=GoToNext?为什么不Set wrdTbl = wrdDoc.Tables(6)并为此工作呢?所有这些代码都可能引用另一个表?

尝试这样的事情:

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