1
For Each cell In Range("A2:A" & Cells(Rows.Count, 1).End(xlUp).Row)
cell.EntireRow.Cut Workbooks("Book2.xlsx").Worksheets("Sheet1").Cells(Rows.Count,1).End(xlUp).Offset(1, 0)
Next cell

Gotta quick question. This piece of code loops through a range, and cuts the entire row / pasting it onto another workbook/worksheet.

However, it cut/pastes the FIRST row successfully. It then skips the 2nd row. And continues after that as expected, cutting/pasting every row (in fact if i set a breakpoint, you can see it hit the first row, skip the 2nd, then run fine & hit all others (H2, H4, H5, etc.). If I change the method to "COPY", it runs fine (H2, H3, H4, etc.).

Note: I can use 'COPY' or some other workarounds. But really am just wondering why 'CUT' behaves this way.

UPDATE: Sorry, I've update the code to CUT instead of COPY. And yea, I understand that that I need a header row in the target sheet. My only question is why the 2nd row is never cut from the source sheet (But when I replace CUT with COPY it works just fine).

4

2 回答 2

2

这真的很有趣。我认为这可能是for导致问题的循环(即Next cell),但在测试中,结果也不是问题。我什至把它放到一个do while循环中并得到相同的结果。最后的手段(这应该是第一个手段:)),我去了MDSN看看他们对 Cut 的评价;这是关键句

切割范围必须由相邻的单元格组成。

虽然我认为您的代码满足此条件,但“相邻单元格”语句让我思考......它是否跳过是因为您正在剪切范围中的第一行,而该范围内没有前一行/单元格?沿着这些思路,我尝试了这段代码,它有效,并且仍然使用.Cut.

Set myRange = Worksheets("Sheet1").Range("A1:A" & _
    Worksheets("Sheet1").Cells(Worksheets("Sheet1").Rows.Count, 1).End(xlUp).Row)
i = 2
Do While i <= myRange.Rows.Count
    myRange.Cells(i, 1).EntireRow.Cut _
        Worksheets("Sheet2").Cells(Worksheets("Sheet2"). _
             Rows.Count, 1).End(xlUp).Offset(1, 0)
    i = i + 1
Loop

我创建了一个范围,该范围比原始范围多一行,但从同一点开始,现在是该范围的第二行。由于这行得通,这让我相信在切割时,excel正在使用前一行来设置切割后当前行的指针。因为当您剪切第一行时没有前一行,所以它会跳过直到它能够这样做,这解释了为什么剪切第一行没有返回所需的结果。

于 2013-10-31T15:38:11.117 回答
0

我没有在您的代码中看到您正在剪切该行的位置,因此我假设您在复制该行后也将其删除。如果是这种情况,请注意,当您删除一行时,它下面的行会向上移动。这意味着如果cell.Row= 12 并且您删除了第 12 行,即使第 12 行现在包含第 13 行的内容,下一次迭代也会查看第 13 行。

通常为了避免这一点,它会通过循环(For i = 1 to 10 Step - 1)向后迭代。但是,您不能通过For Eachstatement向后迭代。

试试这个:

For i = 2 to Cells(Rows.count, 1).End(xlUp).Row Step - 1  
    'Put your code here  
    'Tip: use Cells(i,"H") to reference each cell in column H
Next i

我的问题是您为什么不一次读/写该范围内的所有内容?如果需要复制该范围内的每一行,为什么不一次复制/粘贴所有内容?

Dim Rng as Range  
Set Rng = Range("H2:N" & Cells(Rows.count, 1).End(xlUp).Row)  
'Note I changed the second column reference. Modify this to whichever is the last column in your range.  
Rng.copy Workbooks("Blank1.xlsx").Worksheets("Sheet1").Cells(Rows.count,
1).End(xlUp).Offset(1, 0)
Rng.Clear
于 2013-10-30T18:59:54.373 回答