简体   繁体   中英

If and Do Until Loop EXCEL VBA

New to VBA if someone could help me what im doing wrong here. Trying to run a loop such that it looks for a specific text, starts the loop then stops at a specific point. The loops is such that I want it to copy some values below in my sheet hence a is 55. Im facing the error Block IF without End If

Here is the code:

Private Sub CommandButton3_Click()
For y = 1 To 15 Step 5
Dim x As Double
Dim a As Double
x = 1
a = 55
If Cells(x, y).Value = "Text1" Then
Do Until Cells(x, y).Value = "Text2"
Cells(a, y) = Cells(x, y).Value
Cells(a, y + 1) = Cells(x, y + 1)
x = x + 1
a = a + 1


Loop


End Sub

Indenting is the way forward, you have a for statement with no next and an if with no End If :

Private Sub CommandButton3_Click()
    For y = 1 To 15 Step 5
        Dim x As Double
        Dim a As Double
        x = 1
        a = 55
        If Cells(x, y).Value = "Text1" Then
            Do Until Cells(x, y).Value = "Text2"
                Cells(a, y) = Cells(x, y).Value
                Cells(a, y + 1) = Cells(x, y + 1)
                x = x + 1
                a = a + 1
            Loop
        End If
    Next y
end sub

Besides the issues I mentioned in the comments to your post, if I understood you correctly, you want to loop on cells at Column A, find the first "Text1", then copy all the cells to row 55 and below, until you find "Text2". If that's the case, try the code below :

Private Sub CommandButton3_Click()

Dim x As Long, y As Long
Dim a As Long
Dim LastRow As Long

With Worksheets("Sheet1") '<-- modify "Sheet1" to your sheet's name
    For y = 1 To 15 Step 5

        x = 1  '<-- reset x and a (rows) inside the columns loop
        a = 55 '<-- start pasting from row 55

        LastRow = .Cells(.Rows.Count, y).End(xlUp).Row
        While x <= LastRow '<-- loop until last row with data in Column y
            If .Cells(x, y).Value Like "Text1" Then
                Do Until .Cells(x, y).Value = "Text2"
                    .Cells(a, y).Value = .Cells(x, y).Value
                    .Cells(a, y + 1).Value = .Cells(x, y + 1).Value
                    x = x + 1
                    a = a + 1
                Loop
            End If
            x = x + 1
        Wend
    Next y
End With

End Sub

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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