调整每个变量

时间:2016-03-30 04:04:31

标签: excel vba excel-vba

我遇到了一些我认为非常基本的问题。有人可以帮忙吗?

如何在For Each循环中调整“cell”值?由于我删除了一行,我的“单元格”计数器会在每次删除时被抛弃并跳过一行。

我想我可以通过调整计数器来修复它,但需要替换:Set cell = cell - 1

For Each row In pipelineRange.Rows
  For Each cell In row.Cells
    If cell.Value = "EXIT" Then
       cell.EntireRow.Copy Destination:=Worksheets("EXITS").Range("A" & Sheets("EXITS").Range("B" & Rows.Count).End(xlUp).row + 1)
       Sheets("PIPELINE TRACKER").Activate
       cell.EntireRow.Delete
       Set cell = cell - 1
    ElseIf cell.Value = 1 Then
       cell.EntireRow.Copy Destination:=Worksheets("COMPLETED").Range("A" & Sheets("COMPLETED").Range("B" & Rows.Count).End(xlUp).row + 1)
       Sheets("PIPELINE TRACKER").Activate
       cell.EntireRow.Delete
       Set cell = cell - 1
    End If
 Next cell
Next row

1 个答案:

答案 0 :(得分:1)

删除时总是向后退以避免这种情况。例如:

For X = Range("A" & Rows.count).end(xlup).row to 2 step -1
    If Range("A" & X).Text = "Delete Me" then rows(X).delete
Next

我们知道范围的第一行:pipelineRange.Row如果我们将它们加在一起然后减去1,我们也知道此处pipelineRange.Rows.Count范围内的行数我们将得到最后一行范围

这样的事可能

Sub Something()
Dim X As Long
For X = pipelineRange.Row + pipelineRange.Rows.Count - 1 To pipelineRange.Row Step -1
    For Each cell In Rows(X).Cells
        If cell.Value = "EXIT" Then
           cell.EntireRow.Copy Destination:=Worksheets("EXITS").Range("A" & Sheets("EXITS").Range("B" & Rows.Count).End(xlUp).Row + 1)
           Sheets("PIPELINE TRACKER").Activate
           cell.EntireRow.Delete 'You could change this for rows(X).delete if you like
        ElseIf cell.Value = 1 Then
           cell.EntireRow.Copy Destination:=Worksheets("COMPLETED").Range("A" & Sheets("COMPLETED").Range("B" & Rows.Count).End(xlUp).Row + 1)
           Sheets("PIPELINE TRACKER").Activate
           cell.EntireRow.Delete 'You could change this for rows(X).delete if you like
        End If
    Next
Next
End Sub