2017-07-06 53 views
0

绅士,对于下一个环路问题

我为一个小问题而斗争,并因为他们而变得易怒。我真的很感谢你的建议。

我在工作簿中有一个名为“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 
+0

Cześć;)有你在'设置obecnyLok'奇怪的事情。 'pokoj'是'najemcy'表中的一个单元格。从这个单元格中,你右移6个单元格,从该单元格中取出地址,并用'najemcy.Range'去到这个地址。所以你只是回到同一个单元格。你可以用它来代替:'Set obecnyLok = pokoj.Offset(0,6).End(xlDown)'。 –

+0

好点!谢谢。 – neke

回答

0

当您使用.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