玖叶教程网

前端编程开发入门

VBA|如何选择数据区域的最后一行、最后一列、最后一个单元格

Excel对现有数据进行操作时,常需要确定最后一行、最后一列、最后一个单元格的具体位置。

1 工作的总行数、列数

Sub totalCells()
    r = cells.Rows.Count
    c = cells.Columns.Count
    Debug.Print r, c         '1048576       16384
End Sub

2 有内容区域某列的最后一行

Sub lastRow()
    lrow = Range("A" & Rows.Count).End(xlUp).row + 1  'A列
    Range("A" & lrow) = lrow
End Sub

Range("A" & Rows.Count).End(xlUp)表示人有工作表最后一行开始往上寻找到有内容的单元格停止

3 有内容区域某行的最后一列

Sub lastCol()
    Lcol = Range(cells(1, Columns.Count), cells(1, Columns.Count)).End(xlToLeft).Column + 1
    Dim cel As Range
    Set cel = cells(1, Lcol)
    '把地址中的列标字母取出来
    cel = Left(cel.Address(True, False), InStr(1, cel.Address(True, False), "#34;, 1) - 1)
    Debug.Print cel.Address(0, 0)
End Sub

Range(cells(1, Columns.Count), cells(1, Columns.Count))表示取得第一行最后一列的单元格。

End(xlToLeft)表示从此单元格开始往左找到有内容单元格为止。

4 数据区域的最后一个单元格

可以利用Range对象的Find方法

Sub 数据区域的最后一个单元格()
    Dim row As Integer
    Dim col As Integer
    row = cells.Find("*", Range("A1"), xlFormulas, , xlByRows, xlPrevious).row
    ' 表示从A1的反方向开始按行查找到有内容的单元格为止
    col = cells.Find("*", Range("A1"), xlFormulas, , xlByColumns, xlPrevious).Column
     ' 表示从A1的反方向开始按列查找到有内容的单元格为止
    cells(row, col).Select
    Debug.Print cells(row, col).Address(0, 0)
End Sub

Find(what,after,lookIn,lookAt,searchOrder,searchDirection,matchCase,matchbyte,searchFormat)

必选的参数只有what,表示要查找的内容,可以使用通配符*或?。

after表示查找的起始单元格。

lookIn表示查找的内容,可以是值、公式 、批注。

lookat表示精确或模糊查找。

searchOrder表示按行或按列查找。

searchDirection表示查找方向:xlNext或xlPrevious。

matchCase表示是否匹配大小写。

matchbyte表示双字节或单字节查找。

searchFormat表示查找格式。

返回值:返回一个Range对象,表示查找到的第一个符合条件的单元格,否则返回Nothing。

        Dim rng As Range
        Set rng = Range("A5").Find(".")
        If rng Is Nothing Then
            Range("A20") = "Nothing"
        Else
            Range("A20") = rng
        End If
        Range("A11") = Application.WorksheetFunction.Find(".", [A5], 1)

-End-

发表评论:

控制面板
您好,欢迎到访网站!
  查看权限
网站分类
最新留言