您的位置:首页 > 编程语言 > VB

Excel VBA获取最后一行列

2015-11-04 21:17 591 查看
测试excel文件:



VBA代码:

Function getLastRow()

Debug.Print "End(xlUp):" & Sheets(1).[A65536].End(xlUp).Row

Debug.Print "usedRange:" & ActiveSheet.UsedRange.Rows.Count

Debug.Print "find * :" & ActiveSheet.Cells.Find(What:="*", After:=[A1], SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row

Debug.Print "xlCellTypeLastCell: " & ActiveSheet.Cells.SpecialCells(xlCellTypeLastCell).Row

End Function

运行结果:

End(xlUp):9

usedRange:16

find * :10

xlCellTypeLastCell: 16

结论(几种方式的比较):

方法1:ActiveSheet.Range("A65535").End(xlUp).Row

1. 只能取得对应列的最后一行(本例是A列)。

2. 高低版本不兼容,2007版最大行数增加以后,就不能用65536了,而要用1048576。

可以先判断再决定用哪个数字,即用下列语句代替原来的一句,假定文件名变量为rptfile:

If Right(rptfile, 3) = "xls" Then

maxrow = [A65536].End(xlUp).Row

Else

maxrow = [A1048576].End(xlUp).Row

End If

方法2:ActiveSheet.UsedRange.Rows.Count

1. 即使行仅仅设置了格式,没有内容,也被算成最后一行。

2. 在工作表进行对删除或清除操作时也会变得比实际情况大。

方法3:ActiveSheet.Cells.Find

1. 只计算有内容的行,没有格式的行不计算。

方法4:ActiveSheet.Cells.SpecialCells(xlCellTypeLastCell).Row

效果同方法2。

获取最后一行/列代码示例:

Function getLastRow()

Debug.Print "End(xlUp):" & Sheets(1).[A65536].End(xlUp).Row

Debug.Print "usedRange:" & ActiveSheet.UsedRange.Rows.Count

Debug.Print "find * :" & ActiveSheet.Cells.Find(What:="*", After:=[A1], SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row

Debug.Print "xlCellTypeLastCell: " & ActiveSheet.Cells.SpecialCells(xlCellTypeLastCell).Row

End Function

Function getLastCol()

Debug.Print "End(xlToLeft):" & ActiveSheet.Range("IV1").End(xlToLeft).Column

Debug.Print "usedRange:" & ActiveSheet.UsedRange.Columns.Count

Debug.Print "find * :" & ActiveSheet.Cells.Find(What:="*", After:=[A1], SearchOrder:=xlByColumns, SearchDirection:=xlPrevious).Column

Debug.Print "xlCellTypeLastCell: " & ActiveSheet.Cells.SpecialCells(xlCellTypeLastCell).Column

End Function
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: