有编译错误的代码:不执行循环。但是在代码中做错了吗?

时间:2019-09-12 20:18:57

标签: excel vba loops compiler-errors

我仍然收到编译错误:Loop without Do,即使我在代码中写了Do。我想念什么?

Sub SearchForString()

    Dim StartCell As Integer
    Dim EndCell As Integer

    StartCell = 2
    EndCell = 545

    Do While StartCell < EndCell

    Sheets("tian_corp_donations_Aug2019_how").Activate
    Sheets("tian_corp_donations_Aug2019_how").Select

    With ThisWorkbook.Worksheets("tian_corp_donations_Aug2019_how")

        'If value in column E = "Company_Name", copy entire row to Sheet2
        If Range("B:StartCell").Value = "George Weston Limited" Then
        'Select row in Sheet1 to copy
            Rows(StartCell).Select
            Selection.Copy
        'Paste row into Sheet2 in next row
            Sheets("Sheet2").Select
            Rows(StartCell).Select
            ActiveSheet.Paste
        'Move counter to next row
        'LCopyToRow = LCopyToRow + 1
            Exit Do                
        End If

        'Go back to Sheet1 to continue searching
        Sheets("tian_corp_donations_Aug2019_how").Select

        StartCell = StartCell + 1       

    Loop                

End Sub

1 个答案:

答案 0 :(得分:0)

如果我了解您期望的输出是什么,则不确定Do Loop是最佳选择。也许For Each会更好。试试这个:

Sub SearchForString()

    Dim StartCell As Integer
    Dim EndCell As Integer

    StartCell = 2
    EndCell = 545

    Sheets("tian_corp_donations_Aug2019_how").Activate
    Sheets("tian_corp_donations_Aug2019_how").Select

    Dim Rng As Range
    Set Rng = Range("E2:E545")

    Dim cell As Range
        For Each cell In Rng
        'If value in column E = "Company_Name", copy entire row to Sheet2
            If Cells(StartCell, "E").Text = "George Weston Limited" Then
            'Select row in Sheet1 to copy
                Rows(StartCell).Select
                Selection.Copy
            'Paste row into Sheet2 in next row
                Sheets("Sheet2").Select
                Rows(StartCell).Select
                ActiveSheet.Paste
            'Move counter to next row
            'LCopyToRow = LCopyToRow + 1
            Else
            End If        

        'Go back to Sheet1 to continue searching
        Sheets("tian_corp_donations_Aug2019_how").Select

        StartCell = StartCell + 1

        Next cell   

End Sub