Excel VBA获取最后一行列

来源:互联网 发布:java预处理指令 编辑:程序博客网 时间:2024/05/22 13:06

测试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

 

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

方法1ActiveSheet.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

 

方法2ActiveSheet.UsedRange.Rows.Count

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

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

 

方法3ActiveSheet.Cells.Find

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

 

方法4ActiveSheet.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

0 0
原创粉丝点击