excel - 对于每个单元格...下一个单元格循环仅工作一次

标签 excel vba loops foreach

我的代码在预定义范围“r”中查找值为“已完成”的单元格,但使用 For Each Cell 和 Next Cell 命令不会循环代码以查找多个“已完成”单元格。

我错过了什么?任何帮助,将不胜感激。

Sub Move_Burn()

Dim Msg As String, Ans As Variant

  Msg = "Are you sure you want to move the completed pumps?"

  Ans = MsgBox(Msg, vbYesNo)

  Select Case Ans

Case vbYes

Dim r As Range, cell As Range, mynumber As Long, r2 As Range

Set r = Range("AR15:AR1000")
Set r2 = Range("AF15:AF1000")

mynumber = 1
For Each cell In r
    If cell.Value = "Completed" Then
    Range("AT15:BN15").Select
    Selection.Insert Shift:=xlDown, CopyOrigin:=xlFormatFromLeftOrAbove
    Range("AT15:BN15").Interior.ColorIndex = xlNone

    End If

    If cell.Value = "Completed" Then
    cell.Select
    cell.Value = "Delete"
    Range(ActiveCell, ActiveCell.Offset(0, -20)).Select
    Selection.Copy
    Range("AT15").Select
    ActiveSheet.Paste

    Range("BN15").ClearContents

    End If

    If cell.Value = "Delete" Then
    cell.Select
    Range(ActiveCell, ActiveCell.Offset(0, -20)).Select
    Selection.Delete Shift:=xlUp

    End If

    Next cell

Case vbNo
  GoTo Quit:
    End Select
Quit:

  End Sub

最佳答案

您正在删除单元格,因此您需要向后循环。

将您的循环更改为:

For i = 1000 To 15 Step -1
    '// Your code here

    '// Instead of referring to cell - use Range("AR" & i) e.g.

    If Range("AR" & i).Value = "Completed" Then
        '// rest of code
    End If

Next

关于excel - 对于每个单元格...下一个单元格循环仅工作一次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40279130/

相关文章:

excel - 未选择的组合框当前值的 ListIndex

javascript - 使用 Javascript 在特定数组值之前添加所有数组值

r - 使用循环计算列的累积和

excel - 比较多维数组中的元素

java - jXLS jx :image ends with java. lang.IllegalArgumentException: imgBean 值必须包含图像字节

c# - 如何通过行索引和列索引获取单元格的值

excel - 从 VBS 运行 VBA 宏时出现问题

database - VBA 如何识别列的内容是否为数字?

vba - 在 Excel VBA 中选择工作表范围

python - 在 Python 脚本中循环运行 Bash 命令