对于下一个循环问题

For next loop issue

先生们,

我为一个小问题而苦恼,因为他们而变得焦躁不安。非常感谢您的建议。

我在工作簿中有一个名为“najemcy”的工作表。在此工作表中:A2=3,A7=2,A12=1。合并了以下单元格:A2:A6、A7:A11、A12:A16。 G 列中有以下值:G2=550、G3=55、G7=650、G8=11 G12=550.

宏应该找到 G 列中的最后一个值:范围 A2:A6、A7:A11、A12:A16。这意味着我希望收到 3 次 msgbox,地址为:$G$4、$G$8、$G$12,但我得到的不是 $G$12,而是 $G$1048576

Public Sub helpMe()

Dim najemcy As Worksheet
Dim pokoj As Range
Dim pokNr As Integer
Dim obecnyLok As Range

    For pokNr = 3 To 1 Step -1
        Set najemcy = Sheets("Najemcy")

        Set pokoj = najemcy.Range("A1:A100").Find(What:=pokNr, LookIn:=xlValues, _
        LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
        MatchCase:=False, SearchFormat:=False)
'            MsgBox pokoj.Address

        Set obecnyLok = najemcy.Range(pokoj.Offset(0, 6).Address).End(xlDown)
        MsgBox obecnyLok.Address

    Next
End Sub

当您使用 .end(xlDown) 时,它会下降直到遇到空白行,但如果当前行下方的第一行是空白,它会继续前进。

解决此问题的一种方法是在使用 .end(xlDown)

之前检查下一行是否为空
Public Sub helpMe()

Dim najemcy As Worksheet
Dim pokoj As Range
Dim pokNr As Integer
Dim obecnyLok As Range

For pokNr = 3 To 1 Step -1
    Set najemcy = Sheets("Najemcy")

    Set pokoj = najemcy.Range("A1:A100").Find(What:=pokNr, LookIn:=xlValues, _
    LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
    MatchCase:=False, SearchFormat:=False)
        'MsgBox pokoj.Address

    If najemcy.Range("G" & pokoj.Row + 1).Value = "" Then
        Set obecnyLok = najemcy.Range(pokoj.Offset(0, 6).Address)
    Else
        Set obecnyLok = najemcy.Range(pokoj.Offset(0, 6).Address).End(xlDown)
    End If
    MsgBox obecnyLok.Address

Next
End Sub