宏不完全执行

时间:2017-11-01 20:57:20

标签: excel vba excel-vba

我一直在研究Archives:它选择具有正确单元格值的行并将它们移动到另一个选项卡(同时删除原始选项卡中的行)。

我的宏工作得非常好,但我决定更改我的文件并使用不同的新标签。当我在新选项卡中计算我的宏时,它在右侧行上运行并删除它们,但不会将它们复制到我的“归档选项卡”中:

 Sub Archive_Ongoing()

Test 2 : works for 2 arguments.

    Dim xRg As Range
    Dim xCell As Range
    Dim I As Long
    Dim J As Long
    Dim K As Long
    I = Worksheets("B90_Projects_OnGoing").UsedRange.Rows.Count
    J = Worksheets("B90_Projects_Archived").UsedRange.Rows.Count

    If J = 1 Then
       If Application.WorksheetFunction.CountA(Worksheets("B90_Projects_Archived").UsedRange) = 0 Then J = 0
    End If
    Set xRg = Worksheets("B90_Projects_OnGoing").Range("O1:O" & I)
    Set yRg = Worksheets("B90_Projects_OnGoing").Range("T1:T" & I)
    On Error Resume Next
        Application.ScreenUpdating = False
    For K = 1 To xRg.Count
        If CStr(xRg(K).Value) = "Closed" And CStr(yRg(K).Value) <> "" Then
            xRg(K).Selection.Copy Destination:=Worksheets("B90_Projects_Archived").Range("A" & J + 1)
            xRg(K).EntireRow.Delete
            If CStr(xRg(K).Value) = "Closed" Then
                K = K - 1
            End If
            J = J + 1
        End If
    Next
    Application.ScreenUpdating = True

End Sub'

任何人都可以解释原因吗?

1 个答案:

答案 0 :(得分:0)

因为你在FOR循环中递减K变量,这也是递增它。你的K变量永远不会改变。评论K = K - 1并报告回来?

如果你是故意这样做来评估/删除一行并将下一个值向上移动那么你可能希望有一个K2变量,你可以这样增加:

For K = 1 To xRg.Count
    If CStr(xRg(K - K2).Value) = "Closed" And CStr(yRg(K - K2).Value) <> "" Then
        xRg(K - K2).Selection.Copy Destination:=Worksheets("B90_Projects_Archived").Range("A" & J + 1)
        xRg(K - K2).EntireRow.Delete
        If CStr(xRg(K - K2).Value) = "Closed" Then
            K2 = K2 + 1
        End If
        J = J + 1
    End If
Next