如何在子例程中修复运行时9-工作或失败

时间:2019-05-08 02:26:33

标签: excel vba printing ms-error-9

我的独立Workbook子例程可用于许多调用,但对于这些调用却失败。这是重现该问题的最简单示例。

手动设置打印分页符可提供预期的结果。这些潜艇工作很多张,失败了两张。隐藏了许多列-使打印输出保持在打印机的范围内。

 this works

    BMPRangeSetup
    MyPageSetup
    DownPageBreaks
    ActiveWindow.SelectedSheets.PrintOut From:=1, To:=1, Copies:=1, Collate _
        :=True

this fails

    CMPRangeSetup
    MyPageSetup
    DownPageBreaks
    ActiveWindow.SelectedSheets.PrintOut From:=1, To:=1, Copies:=1, Collate _
        :=True

BMPRangeSetup contains:

    ActiveSheet.PageSetup.PrintArea = "$A$1:$BH$210"

Where CMPRangeSetup has:

    ActiveSheet.PageSetup.PrintArea = "$A$1:$BV$210"

the failure shows at Range("A111") 

    Sub DownPageBreaks()
      ActiveSheet.ResetAllPageBreaks
      ActiveSheet.HPageBreaks(1).Location = Range("A61")
      ActiveSheet.HPageBreaks(2).Location = Range("A111")
      ActiveSheet.HPageBreaks(3).Location = Range("A161")
    End Sub

2 个答案:

答案 0 :(得分:0)

@BigBen是正确的,.HPageBreaks有时会失败。试试这个:

With ActiveSheet
     .ResetAllPageBreaks
     .HPageBreaks.Add Range("A61")
     .HPageBreaks.Add Range("A111")
     .HPageBreaks.Add Range("A161")
End With

在设置分页符之前将ActiveCell移出受影响的区域也可能会有所帮助:

Dim sCell as String

sCell = ActiveCell.Address
Range("AA1111").Activate
....
Range(sCell).Activate

答案 1 :(得分:0)

谢谢@AcsErno! 我发现这可行!

 Range("A212").Activate     ' a cell outside print range.
 With ActiveSheet
     .ResetAllPageBreaks
     .HPageBreaks.Add Range("A61")
     .HPageBreaks.Add Range("A111")
     .HPageBreaks.Add Range("A161")
 End With