简体   繁体   English

Excel VBA For 循环与 UsedRange 计数错误

[英]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).我只是想知道为什么我的代码总是在 n = 19(原始 maxRow 计数)时退出。 I added maxRow = maxRow +1 because I inserted one row so that it doesn't exit until it is finished.我添加了 maxRow = maxRow +1 因为我插入了一行,这样它在完成之前不会退出。

What I am trying to do, is to remove the two cells (D&E) and inserting a row underneath until D&E is empty.我想要做的是删除两个单元格(D&E)并在下面插入一行,直到 D&E 为空。

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.你没有回答我的问题,我准备了一个答案,假设必要的代码必须用它们的右邻居 (F:G) 替换 D:E 中的单元格,并在这样的处理范围之后插入一行。 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...如果我的假设是错误的,请更好地解释(用文字......)你需要完成什么......

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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