简体   繁体   English

Excel VBA将打印区域设置为包含数据的最后一行

[英]Excel VBA set print area to last row with data

I have an Excel table with a sheet "CR" where columns A to K are filled, with the first row being a header row. 我有一个带有表“CR”的Excel表,其中填充了列A到K,第一行是标题行。

Rows 1-1000 are formatted (borders) and column A contains a formula to autonumber the rows when data in column F is entered. 行1-1000格式化(边框),列A包含一个公式,用于在输入F列中的数据时自动调整行数。

Sheet "CR" is protected to prevent users from entering data in column A (locked). 工作表“CR”受到保护,以防止用户输入A列(已锁定)中的数据。

Using the Workbook_BeforePrint function, I'm trying to set the print area to columns A to K and to the last row of column A that contains a number. 使用Workbook_BeforePrint函数,我正在尝试将打印区域设置为A到K列以及包含数字的A列的最后一行。

My code (in object 'ThisWorkbook') is as follows: 我的代码(在对象'ThisWorkbook'中)如下:

Private Sub Workbook_BeforePrint(Cancel As Boolean)
Dim ws As Worksheet
Dim lastRow As Long

Set ws = ThisWorkbook.Sheets("CR")

' find the last row with data in column A
lastRow = .Cells(.Rows.Count, 1).End(xlUp).Row

ws.PageSetup.PrintArea = ws.Range("A1:K" & lastRow).Address
End Sub

However, when I click File -> Print, the range of columns A to K up to row 1000 is displayed instead of only the rows that have a number in column A. What am I doing wrong? 但是,当我单击文件 - >打印时,将显示列A到K到行1000的范围,而不是仅显示在列A中有数字的行。我做错了什么?

Change: 更改:

lastRow = .Cells(.Rows.Count, 1).End(xlUp).Row

To: 至:

lastRow = [LOOKUP(2,1/(A1:A65536<>""),ROW(A1:A65536))]

.End(...) will act like ctrl + arrow-key. .End(...)行为类似于ctrl + arrow-key。 if the cell has a formula (which looks empty due to the formula, then it will still stop there... another way would be the use of evaluate (if you do not want to loop) like this: 如果单元格有一个公式(由于公式看起来是空的,那么它仍将停在那里......另一种方式是使用evaluate(如果你不想循环),如下所示:

lastRow = .Evaluate("MAX(IFERROR(MATCH(1E+100,A:A,1),0),IFERROR(MATCH(""zzz"",A:A,1),0))")

This will give the last row (which has a value in column A). 这将给出最后一行(在A列中有一个值)。

Also check if there are hidden values (looking empty due number format or having characters you can't see directly. Try to go below row 1000 in column A (select a cell after A1000 in column A) and hit ctrl+up to validate where it stops (and why). 还要检查是否存在隐藏值(看起来是空的到期数字格式或有直接看不到的字符。尝试在A列的第1000行下面(在A列中选择A1000后的单元格)并按ctrl +向上以验证在哪里它会停止(以及为什么)。

EDIT: 编辑:
(regarding your comment) (关于你的评论)

"" still leads to a "stop" for the .End(...) -command. ""仍然导致.End(...)命令的“停止”。 So either use my formula, translate the formula into vba or loop the cells it get the last value. 所以要么使用我的公式,将公式转换为vba,要么循环它获得最后一个值的单元格。 Also Find is a good tool (if not doing it over and over for countless times). Find也是一个很好的工具(如果不是无数次地反复进行)。

lastRow = .Cells.Find("*", .Range("B1"), xlValues, , xlByColumns, xlPrevious).Row

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM