确定打印页面中的列数

在Excel 2007中,我有一个工作表只包含less数几个单元格中的数据(很好,在一页宽/高)。 例如,说工作表只包含单元格A1中的数据。 如何使用VBA来确定适合单个打印页面的列数? 换句话说,我怎样才能确定最右边的列,我可以添加数据,而不会导致打印一张额外的表格。 一些额外的评论:

  • 我不设置打印区域。 如果我是,那么我只是使用相同的范围…但我不是。

  • 我无法使用UsedRange ,因为使用的范围比实际适合打印页面的宽度/高度的范围要小得多。

  • 我不能使用ActiveWindow.VisibleRange因为它不限于单个页面宽度/高度。

我已经search和search,但无法find解决scheme来完成这个看似简单的任务。 我主要发现涉及UsedRangeVisibleRange和打印区域的场景,但是那些帮助不了我。

编辑

这里是我正在使用的函数的最终版本,这是对所选答案的微调。

 Public Function GetLastColumnBeforeVPageBreak( _ ByRef ws As Worksheet, _ ByVal aVPageBreakNum As Long) As Long Dim isMod As Boolean isMod = False On Error GoTo ErrorHandler GetLastColumnBeforeVPageBreak = ws.VPageBreaks(aVPageBreakNum).Location.Column - 1 ' If necessary, delete the last column with dummy data and reset UsedRange. If isMod Then ws.Cells(ws.Rows.Count, ws.Columns.Count).EntireColumn.Delete r = ws.UsedRange.Rows.Count End If Exit Function ErrorHandler: If Err.Number = 9 Then ' Subscript out of range. ' Ensure there is more than one page by putting something in last cell. isMod = True ws.Cells(ws.Rows.Count, ws.Columns.Count).Value = 1 Err.Clear Resume Else Err.Raise Err.Number End If End Function 

我确定分页符附近有一个工作表属性,所以我在IDE中按F2来打开对象浏览器并在pagebreaksearch。 有一点F1'ing显示有一个Worksheets(1).VPageBreaks(1).Location属性返回一个范围对象。 范围的左侧与第一个垂直分页符alignment,如下所示:

 LastColOnP1 = Worksheets(1).VPageBreaks(1).Location.Column - 1 

会给你一个variables,其中包含最后一列的数字,这些数字将在第一张表的第一页上打印。

或者在一个程序中:

 Sub FindFirstVPageBreak() Dim LastColOnP1 As Long With ActiveSheet 'Ensure there is more than one page by puting something in last column .Cells(1, .Columns.Count) = 1 LastColOnP1 = .VPageBreaks(1).Location.Column - 1 'Delete the last column to allow UsedRange to be reset .Cells(1, .Columns.Count).EntireColumn.Delete End With 'Save to workbook to commit the reset UsedRange If Not ActiveWorkbook.ReadOnly Then ActiveWorkbook.Save 'assumes workbook has been saved previously. End If End Sub 

您可以使用Columns(x).ColumnWidth来计算(iif列包含数据)。 请参阅http://EzineArticles.com/7305778了解更详细的解决scheme。