Search code examples
excelvbaloopsresizedynamic-tables

How to write "Do Until" loop that resizes table?


I'm working with a dynamic table that populates names based on the given weeks data. I have a macro that refreshes and sorts the data as needed but am currently working with the .Resize Range() function to adjust the table based on how the rows populate.

Note: "Login" cells populate based on an IF reference to another sheet: =IF(WSSW!AH126=0,"-",WSSW!AH126)

See table ("Table12") itself below (webdings for privacy) Dynamic Table Problem Area

Prior to including the loop, mnTbl.Resize Range("$A$3:" & lcol & lrow - 1) and mnTbl.Resize Range("$A$3:" & lcol & lrow + 1) did exactly what I needed them to. The trouble started when I wanted the macro to decide which operation to run based on the the last cell in my "Login" column. The currently included Do Until loop freezes my application but I left it for current state visibility. The goal is to have the macro decide if it should add a row or remove one.

Sub TableDrag()
'
' TableDrag Macro
'

'
Dim MAIN As Worksheet
Set MAIN = ThisWorkbook.Sheets("MAIN")

Dim mnTbl As ListObject
Set mnTbl = MAIN.ListObjects("Table12")

Dim lrow As String
Dim val As String


' Find Last Row
lcol = "J"
lrow = mnTbl.Range.Rows(mnTbl.Range.Rows.Count).Row
val = Range("A" & lrow).Value

Do Until val <> "-"
    mnTbl.Resize Range("$A$3:" & lcol & lrow - 1)
    Loop



End Sub

Solution

  • Before entering the loop, val = "-". The loop repeats until val <> "-". But the value of val is never being changed in the loop. val will always be "-", so the loop will never end.

    Similar problem with lrow - 1. The value of lrow is never being changed within the loop. If lrow = 131 before entering your loop, then every loop will just be lrow - 1 = 130.

    Whatever condition the loop is testing, the result of that condition should be changed within the loop. In your case, the value of val should be changed within the loop. Without modifying your code too much, try:

    Do Until Val <> "-"
        lrow = lrow - 1
        mnTbl.Resize Range("$A$3:" & lcol & lrow)
        Val = Range("A" & lrow).Value
    Loop
    

    To clean things up a little, it would be slightly neater to just test the value of Range("A" & lrow).Value, and not resize your range until after the loop:

    Do Until Range("A" & lrow).Value <> "-"
        lrow = lrow - 1
    Loop
    
    mnTbl.Resize Range("$A$3:" & lcol & lrow)