如果和直到循环EXCEL VBA

新的VBA,如果有人可以帮助我在这里做错了什么。 试图运行一个循环,以便查找特定的文本,启动循环,然后在特定点停止。 循环是这样的,我希望它在我的表中复制下面的一些值,因此a是55.我面临的错误块如果没有结束如果

这里是代码:

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 

除了我在你的文章的评论中提到的问题,如果我正确地理解了你,你想循环在A列的单元格,find第一个“Text1”,然后将所有的单元格复制到第55行和下面,直到find“文本2" 。 如果是这种情况,请尝试下面的代码:

 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 

缩进是前进的方向,你有一个没有next一个for陈述, if没有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