使用VBA从单词表中删除列

问题描述 投票:0回答:1

我有一个很长的宏跳转到不同的书签并删除所选表中的列。这是我的宏的一个例子:

If ActiveDocument.Bookmarks.Exists("ProposedOverallObj") = True Then
ActiveDocument.Bookmarks.Item("ProposedOverallObj").Select
Call ApproveProposedOverallObj
End If

然后调用的宏是:

Sub ApproveProposedOverallObj()

Selection.Cut
Selection.GoTo What:=wdGoToBookmark, Name:="Objectives"
With ActiveDocument.Bookmarks
    .DefaultSorting = wdSortByName
    .ShowHidden = False
End With
Selection.PasteAndFormat (wdPasteDefault)
Selection.Tables(1).Columns(5).Delete
Selection.Tables(1).Columns(4).Delete
Selection.Tables(1).Columns(3).Delete
Selection.Tables(1).Columns(2).SetWidth ColumnWidth:=600.5, RulerStyle:= _
    wdAdjustFirstColumn
End If
End Sub 

有时这些运行正常,有时它们会出错并且我收到错误:

“运行时错误'5825':对象已被删除。

基本上它删除第5列和第3列然后错误并说“我不能删除第3列,因为它已被删除”但是......它没有。第3列仍然非常多。

vba ms-word
1个回答
0
投票

可能错误在Select - 它在VBA中一般不太可靠 - How to avoid using Select in Excel VBA

作为一个经验法则,尽可能将对象分配给变量并引用它:

Sub TestMe()

    Dim myTable As Table
    Set myTable = ThisDocument.Tables(1)
    MsgBox "First table has " & myTable.Columns.Count & " columns."

    If myTable.Columns.Count >= 5 Then
        With myTable
            .Columns(5).Delete
            .Columns(4).Delete
            .Columns(3).Delete
        End With
    Else
        MsgBox "Not enough columns!"
    End If

End Sub
© www.soinside.com 2019 - 2024. All rights reserved.