Excel VBA打印自动调整问题

时间:2012-12-29 09:09:49

标签: excel excel-vba vba

我有一个excel VBA打印功能,对于我想在工作簿中打印的每张纸都调用一次

我循环浏览VBA中的工作表并调用此函数。

Sub PrintSheet
  With ActiveSheet

    'lastRow is worked out here....

    'Autofit YTD and SLY
    .Columns("J:J").AutoFit
    .Columns("K:K").AutoFit

    'Autofit email column
    .Columns("F:F").AutoFit

    With .PageSetup
        .Zoom = False
        .FitToPagesWide = 1
        .FitToPagesTall = False
        .Orientation = xlLandscape
        .LeftMargin = Application.InchesToPoints(0.4)
        .RightMargin = Application.InchesToPoints(1)
        .TopMargin = Application.InchesToPoints(0.5)
        .BottomMargin = Application.InchesToPoints(0.5)
        .RightFooter = "&P of &N"

        .PrintArea = "$A$1:$O$" & CStr(lastRow)
    End With

    .PrintOut
 End With
End Sub

我遇到的问题是有时候(随机行为并不总是相同的表格)我自动调整的列拉伸范围非常宽,迫使其他列离开页面。这不是数据相关的,因为您可以再次运行打印例程并打印相同的工作表,以前将列拉出来很好。我正在修改工作表中的所有列值,因为它们首先输入了VBA代码

我没有找到任何具有此行为的模式,除了我说拉伸的列是自动调整的。

有什么想法吗?

1 个答案:

答案 0 :(得分:4)

使用autofit时,我经历了很多次;所以我现在尝试尽可能少地使用它。

你可以做的事情:

1.使用设定的宽度,例如,如果您知道J列始终在47宽度处正常,则使用Columns("D:D").ColumnWidth = 47
2.您可以在子例程的末尾添加一些测试,如下所示:

Sub PrintSheet()

With Excel.ActiveSheet

    'lastRow is worked out here....
    lastRow = .Cells(.Rows.Count, 1).End(Excel.xlUp).Row

    'Autofit YTD / SLY / email
    .Columns("J:J").AutoFit
    .Columns("K:K").AutoFit
    .Columns("F:F").AutoFit

    With .PageSetup
        .Zoom = False
        .FitToPagesWide = 1
        .FitToPagesTall = False
        .Orientation = Excel.xlLandscape
        .LeftMargin = Application.InchesToPoints(0.4)
        .RightMargin = Application.InchesToPoints(1)
        .TopMargin = Application.InchesToPoints(0.5)
        .BottomMargin = Application.InchesToPoints(0.5)
        .RightFooter = "&P of &N"
        .PrintArea = "$A$1:$O$" & lastRow 'CStr(lastRow) <=== & does an implicit conversion
    End With

    'add three checks here <====
    '<==I've picked 100 out of thin air but you need to change this to a value which indicates that it has behaved badly
    If .Columns("J:J").ColumnWidth > 100 Then
        .Columns("J:J").ColumnWidth = 30  '<== you might want to amend 30
    End If
    If .Columns("k:k").ColumnWidth > 100 Then
        .Columns("k:k").ColumnWidth = 30
    End If
    If .Columns("f:f").ColumnWidth > 100 Then
        .Columns("f:f").ColumnWidth = 30
    End If

    .PrintOut

End With
End Sub