没有Next的编译错误-VBA代码

时间:2019-02-06 09:15:04

标签: excel vba for-loop next

我正在尝试编写一些VBA代码,该代码将搜索名为“ 01 Feb 19”的工作表,在(T)列中查找单词“ Deployed”,如果发现该单词,则将整个行复制到一个新的工作表称为“已部署”。我已经添加了一个For循环,我知道我需要添加一个Next,但是我无法弄清楚。

到目前为止,这是我的代码。

Sub CopyRows()    
    Dim cell As Range
    Dim lastRow As Long
    Dim i As Long

    Dim wksh1 As Worksheet
    Set wksh1 = Worksheets("01 Feb 19")

    Dim wksh2 As Worksheet
    Set wksh2 = Worksheets("Deployed")

    lastRow = Range("A" & Rows.Count).End(xlUp).Row 'finds the last row
    i = 1

    For Each cell In wksh1.Range("T1:T" & lastRow) 'looks in T column until the last row
        If cell.Value = "Deployed" Then 'searches for word deployed
            cell.EntireRow.Copy wksh2.Cells(i, 1) 'copies entire row into Deployed work sheet      
        End If
End Sub

1 个答案:

答案 0 :(得分:0)

Next cell循环结束时您缺少For

Sub CopyRows()
    Dim cell As Range
    Dim lastRow As Long
    Dim i As Long

    Dim wksh1 As Worksheet
    Set wksh1 = Worksheets("01 Feb 19")

    Dim wksh2 As Worksheet
    Set wksh2 = Worksheets("Deployed")

    lastRow = Range("A" & Rows.Count).End(xlUp).Row 'finds the last row
    i = 1

    For Each cell In wksh1.Range("T1:T" & lastRow) 'looks in T column until the last row
        If cell.Value = "Deployed" Then 'searches for word deployed
            cell.EntireRow.Copy wksh2.Cells(i, 1) 'copies entire row into Deployed work sheet
            i = i + 1 ' <-- Added so that rows don't overwrite each other. Remove if it is intended to overwrite each row
        End If
    Next cell ' <-- Added
End Sub