【问题标题】:Compile error For without Next - VBA code编译错误 For without Next - VBA 代码
【发布时间】:2019-06-30 04:41:44
【问题描述】:

我正在尝试编写一些 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

【问题讨论】:

  • 对于一个(可能很差的)示例结构来帮助你,看看这个:stackoverflow.com/q/50776026/4961700 还看看这个范围是如何被复制和传递的,你似乎还没有。
  • 谢谢!我现在看看。这一定是我现在在代码中收到消息中断的原因。我对代码几乎一无所知,这是我的第一次尝试,所以感谢您的帮助。

标签: excel vba for-loop next


【解决方案1】:

您在 For 循环结束时缺少 Next cell

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

【讨论】:

  • 您可能还想在循环中增加i 的值。如果这已经解决了您的问题,请不要忘记单击此答案左侧的勾号以将其标记为已解决
  • 谢谢,我刚刚意识到,代码有效,但我只得到最后一行。极好的!这一切都在工作......多么嗡嗡声!下一步是尝试复制标题:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-05-14
  • 1970-01-01
  • 1970-01-01
  • 2017-03-22
  • 2016-01-20
相关资源
最近更新 更多