gpt4 book ai didi

vba - 非连续范围中的最后一行或单元格{不是工作表搜索}

转载 作者:行者123 更新时间:2023-12-02 10:10:16 29 4
gpt4 key购买 nike

首先,这不是典型的新手问题。我正在尝试找到我已经正确创建的范围中的最后一行(或单元格)。

在此示例中,我将两个范围通过并集合并为一个范围。循环遍历范围,我得到了我想要的数据,一切都很好。

Sub Test()

Dim unionRange As Range, currentRow As Range
Set unionRange = Union(Range("A3:C5"), Range("A8:C11"))

For Each currentRow In unionRange.Rows
Debug.Print "Row: " & currentRow.row
Next currentRow

End Sub

这给出了这些结果

Row: 3
Row: 4
Row: 5
Row: 8
Row: 9
Row: 10
Row: 11

但是当我想尝试确定当前行是否是我的范围中的最后一行时,我似乎找不到一种干净的方法来获取该信息。

Sub Test()

Dim unionRange As Range, currentRow As Range
Set unionRange = Union(Range("A3:C5"), Range("A8:C11"))

For Each currentRow In unionRange.Rows
Dim lastRowIndex As Integer

'lastRowIndex = unionRange. ???

If currentRow.row = lastRowIndex Then
MsgBox ("Last Row")
End If

Next currentRow

End Sub

之所以如此困难,是因为我尝试过的每个解决方案都只是在第一个连续组中生成信息,如下所示。

    Debug.Print unionRange.Rows.Count ' 3 (should be 7)
Debug.Print unionRange.Rows(unionRange.Rows.Count).row ' 5 (should be 11)

除了在这之前进行第二次循环之外,还有其他方法可以获取最后一行的地址信息吗?

最佳答案

您需要使用范围的 Areas 属性。当范围不连续时,它包含多个区域。每个区域都是子范围。不幸的是,区域没有以任何方式排序。因此,您需要循环检查每个区域,然后返回最大行。

在下面的示例中,我创建了一个函数,该函数为您提供非连续范围内的最后一行号。测试子将行号打印到 Visual Basic for Applications 编辑器中的立即窗口。

Public Function GetLastRowOfNonContiguousArea(targetRange As Range) As Long
Dim subRange As Range
Dim maxRow As Long, areaMaxRow As Long

maxRow = 0

For Each subRange In targetRange.Areas
areaMaxRow = subRange.Rows(subRange.Rows.Count).Row
If areaMaxRow > maxRow Then maxRow = areaMaxRow
Next subRange

GetLastRowOfNonContiguousArea = maxRow
End Function

Public Sub test()
Dim testRange As Range

Set testRange = Union([A5:A9], [E20:F21], [C1:C3])

Debug.Print GetLastRowOfNonContiguousArea(testRange)
End Sub

关于vba - 非连续范围中的最后一行或单元格{不是工作表搜索},我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37843753/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com