简体   繁体   English

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

[英]Code with compile error: loop without do. But Do is in the code what is wrong?

I keep getting a compiling error: Loop without Do even though I wrote Do in my code. 我一直收到编译错误:即使我在代码中编写了Do ,也Loop without Do What am I missing? 我想念什么?

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

If I understand what your desired output is, I'm not sure a Do Loop is the best option. 如果我了解您想要的输出是什么,则不确定“ Do Loop是否是最佳选择。 Maybe a For Each would work better. 也许For Each会更好。 Try This: 尝试这个:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM