【问题标题】:next without for in excel VBA在excel VBA中没有for
【发布时间】:2019-06-08 10:37:42
【问题描述】:

我同时拥有 next 和 for,但我仍然收到此错误消息说“next without for”。有人可以帮我解决这个错误信息吗?我在这里做错了什么?

Sub CheckCOA()
    new_coa_detected = 0
    Sheets("CAO & other").Select

    With ActiveSheet
        lr = .Cells(.Rows.Count, "A").End(xlUp).Row
        MsgBox "Ref Table Length = " & lr
    End With

    Sheets("Month1").Select

    With ActiveSheet
        lr1 = .Cells(.Rows.Count, "A").End(xlUp).Row
        MsgBox "Month 1 Length = " & lr1
    End With

    For l = 2 To lr1
        code = Cells(l, 1)
        Sheets("CAO & other").Select

        For m = 2 To lr
            If Cells(m, 1) = code Then
                GoTo existing_code
            End If
        Next m
new_code:
        'New code detected
        Sheets("NewCOAsDetected").Select

        With ActiveSheet
            lr_new_coa = .Cells(.Rows.Count, "A").End(xlUp).Row
            Cells(lr_new_coa, 1) = code
            new_coa_detected = 1
            Sheets("Month1").Select

existing_code:
        'No action for existing code. Check next code

    Next l

    If new_coa_detected = 1 Then
        MsgBox "New COA codes have been detected. A list of these COA codes is available under the 'NewCOAsDetected' tab."
    End If
End Sub

【问题讨论】:

标签: excel vba


【解决方案1】:

我认为您缺少“结尾”

        With ActiveSheet
            lr_new_coa = .Cells(.Rows.Count, "A").End(xlUp).Row
            Cells(lr_new_coa, 1) = code
            new_coa_detected = 1
            Sheets("Month1").Select
        End With

我也尝试按照上面提到的@Pᴇʜ 编辑您的代码:

    Option Explicit

Sub CheckCOA()

    Dim new_coa_detected As Long

    new_coa_detected = 0

    With ThisWorkbook.Worksheets("CAO & other")
        lr = .Cells(.Rows.Count, "A").End(xlUp).Row
        MsgBox "Ref Table Length = " & lr
    End With

    With ThisWorkbook.Worksheets("Month1")
        lr1 = .Cells(.Rows.Count, "A").End(xlUp).Row
        MsgBox "Month 1 Length = " & lr1
    End With

    For l = 2 To lr1
        code = ThisWorkbook.Worksheets("Month1").Cells(l, 1)

        For m = 2 To lr
            If ThisWorkbook.Worksheets("CAO & other").Cells(m, 1) = code Then
                GoTo existing_code
            End If
        Next m

new_code:

        'New code detected
        With ThisWorkbook.Worksheets("NewCOAsDetected")
            lr_new_coa = .Cells(.Rows.Count, "A").End(xlUp).Row
            .Cells(lr_new_coa, 1) = code
            new_coa_detected = 1
            Sheets("Month1").Select
        End With

existing_code:

        'No action for existing code. Check next code

    Next l

    If new_coa_detected = 1 Then
        MsgBox "New COA codes have been detected. A list of these COA codes is available under the 'NewCOAsDetected' tab."
    End If

End Sub

【讨论】:

    猜你喜欢
    • 2020-05-15
    • 2013-12-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多