Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/vba/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Excel VBA:获取包含选定范围内数据的最后一个单元格_Vba_Excel - Fatal编程技术网

Excel VBA:获取包含选定范围内数据的最后一个单元格

Excel VBA:获取包含选定范围内数据的最后一个单元格,vba,excel,Vba,Excel,如何使用Excel VBA获取包含特定范围内数据的最后一个单元格,例如a列和B列范围(“a:B”) 您可以尝试几种方法: 使用xlUp 使用特殊单元格 后者有时可能很棘手,并且可能无法按您希望的方式工作 更多提示 您还可以查看以了解可使用的变量选择 Sub test() Dim arrArray As Variant Dim iAct As Integer Dim iHighest As Integer arrArray = Split(Selection.Add

如何使用Excel VBA获取包含特定范围内数据的最后一个单元格,例如a列和B列
范围(“a:B”)

您可以尝试几种方法:

使用xlUp 使用特殊单元格 后者有时可能很棘手,并且可能无法按您希望的方式工作

更多提示
您还可以查看

以了解可使用的变量选择

Sub test()
    Dim arrArray As Variant
    Dim iAct As Integer
    Dim iHighest As Integer
    arrArray = Split(Selection.Address(1, 1, xlR1C1), ":")
    For Count = Right(arrArray(0), 1) To Right(arrArray(1), 1)
        iAct = ActiveSheet.Cells(Rows.Count, Count).End(xlUp).Row
        If iAct > iHighest Then iHighest = iAct
    Next Count
    MsgBox iHighest
End Sub

像下面这样使用
Find
很有用,因为

  • 可以立即找到二维范围内的最后一个(或第一个)单元
  • 测试
    Nothing
    标识空白范围
  • 将在可能不连续的范围内工作(即
    SpecialCells
    range)
将“您的工作表”更改为您正在搜索的工作表的名称

Sub Method2()
    Dim ws As Worksheet
    Dim rng1 As Range
    Set ws = Sheets("YourSheet")
    Set rng1 = ws.Columns("A:B").Find("*", ws.[a1], xlValues, , xlByRows, xlPrevious)
    If Not rng1 Is Nothing Then
        MsgBox "last cell is " & rng1.Address(0, 0)
    Else
        MsgBox ws.Name & " columns A:B are empty", vbCritical
    End If
End Sub

对于
范围(“A:B”)
只需替换
选择
对不起,但是循环查找最后一个单元格,只会浪费时间和资源。请看,这个问题已经被问了一千次了。查看此链接:
Find
确实也值得注意,即使这不是我最喜欢的方法:)对于更多内容,一列/一行-Find是最好的方法(IMHO.)+1.
Sub test()
    Dim arrArray As Variant
    Dim iAct As Integer
    Dim iHighest As Integer
    arrArray = Split(Selection.Address(1, 1, xlR1C1), ":")
    For Count = Right(arrArray(0), 1) To Right(arrArray(1), 1)
        iAct = ActiveSheet.Cells(Rows.Count, Count).End(xlUp).Row
        If iAct > iHighest Then iHighest = iAct
    Next Count
    MsgBox iHighest
End Sub
Sub Method2()
    Dim ws As Worksheet
    Dim rng1 As Range
    Set ws = Sheets("YourSheet")
    Set rng1 = ws.Columns("A:B").Find("*", ws.[a1], xlValues, , xlByRows, xlPrevious)
    If Not rng1 Is Nothing Then
        MsgBox "last cell is " & rng1.Address(0, 0)
    Else
        MsgBox ws.Name & " columns A:B are empty", vbCritical
    End If
End Sub