更改单词表列宽并将图片从excel vba插入单词时出现问题

时间:2018-11-08 20:09:31

标签: excel vba ms-word

我正在尝试使用vba将文本,表格和图片组合成来自excel文件的word文件。以下代码大多数时候都可以工作。但是,偶尔会出现错误462。

我四处搜寻。一些评论说它的出现是因为存在不合格的参考文献。但是,我不知道什么是不合格的参考。一件奇怪的事:通常第一次运行就可以了。之后,此错误通常仅在偶数次出现。我确信无论代码是否成功执行,每次都会关闭word文件。

这是代码。我在注释中指出发生错误的行。

Dim WordApp As Object, WordDoc As Object

Set WordApp = New Word.Application

With WordApp
    .Visible = True

    Set WordDoc = .Documents.Add
    .ActiveDocument.Select
    With .Selection
    'narrative
    Sheet3.Range("G2").Copy
    .PasteExcelTable False, False, False

    'IO
    Sheet2.Range("A1","B11").Copy
    .PasteExcelTable False, False, False
    WordDoc.Tables(1).Columns(1).Width = InchesToPoints(1.5) 'Error 462 appears periodically on this line
    WordDoc.Tables(1).Columns(2).Width = InchesToPoints(4.5)
    WordDoc.Tables(1).Rows.Height = 20

    'HMI
    Sheet9.Range("A4").Copy
    .PasteExcelTable False, False, False
    Sheet9.Shapes("Group_Htr").Copy
    .PasteSpecial   
    .ShapeRange(1).WrapFormat.Type = wdWrapInline
    .EndKey unit:=wdStory
    'P&ID
    .TypeParagraph
    .InsertBreak Type:=wdSectionBreakNextPage
        With .PageSetup
            .LineNumbering.Active = False
            .Orientation = wdOrientPortrait
            .TopMargin = InchesToPoints(1)
            .BottomMargin = InchesToPoints(1)
            .LeftMargin = InchesToPoints(1)
            .RightMargin = InchesToPoints(1)
            .Gutter = InchesToPoints(0)
            .HeaderDistance = InchesToPoints(0.5)
            .FooterDistance = InchesToPoints(0.5)
            .PageWidth = InchesToPoints(11)
            .PageHeight = InchesToPoints(17)
            .FirstPageTray = wdPrinterDefaultBin
            .OtherPagesTray = wdPrinterDefaultBin
            .SectionStart = wdSectionNewPage
            .OddAndEvenPagesHeaderFooter = False
            .DifferentFirstPageHeaderFooter = False
            .VerticalAlignment = wdAlignVerticalTop
            .SuppressEndnotes = False
            .MirrorMargins = False
            .TwoPagesOnOne = False
            .BookFoldPrinting = False
            .BookFoldRevPrinting = False
            .BookFoldPrintingSheets = 1
            .GutterPos = wdGutterPosLeft
            If .Orientation = wdOrientPortrait Then
                .Orientation = wdOrientLandscape
            End If
        End With
    Sheet10.Range("A4").Copy
    .PasteExcelTable False, False, False
    Sheet10.Shapes("Group_Htr").Copy
    .PasteSpecial                   'Error 4198 appears occasionally on this line
    End With
    .Activate

End With

1 个答案:

答案 0 :(得分:0)

出现错误的原因是因为InchesToPoints不是Excel的一部分,而Excel是运行代码的地方。此方法特定于Word,因此需要对Word.Application的引用。将.放在每次出现的前面,以便它从WordApp中拾取With

WordDoc.Tables(1).Columns(1).Width = .InchesToPoints(1.5)