0

我有一个 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 代码输入

除了我所说的拉伸列是自动调整的列之外,我无法找到任何具有这种行为的模式。

有什么想法吗?

4

1 回答 1

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
于 2012-12-29T12:31:51.447 回答