简体   繁体   中英

Excel VBA For loop with UsedRange Count Error

maxRow = ws.UsedRange.EntireRow.Count

For n = 1 To maxRow

    Do While Not IsEmpty(ws.Range("D" & n).Value)
    
    ws.Range("D" & n & ":" & "E" & n).Delete shift:=xlShiftToLeft
    Rows(n + 1).Insert shift:=xlShiftDown
    maxRow = maxRow + 1
    
    Loop

Next n

I was just wondering why my code always exit when n = 19 (number of original maxRow count). I added maxRow = maxRow +1 because I inserted one row so that it doesn't exit until it is finished.

What I am trying to do, is to remove the two cells (D&E) and inserting a row underneath until D&E is empty.

Thanks

You did not answer my question and I prepared an answer based on the assumption that the necessary code must replace the cells in D:E with their right neighbors (F:G) and insert a row after such a processed range. If this assumption is correct, please test the next code:

Sub testDeleteRangeInsertRow()
 Dim ws As Worksheet, n As Long
 
 Set ws = ActiveSheet

   n = 2
    Do While Not IsEmpty(ws.Range("D" & n).value)
    
       ws.Range("D" & n & ":" & "E" & n).Delete Shift:=xlShiftToLeft
       Rows(n + 1).Insert Shift:=xlShiftDown
       n = n + 2
    Loop
End Sub

If my assumption is wrong, please better explain (in words...) what do you need to accomplish...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM