Vba基于搜索动态值从多个工作表复制行并将其粘贴到另一个新工作簿中时出现问题

时间:2018-01-03 06:50:21

标签: excel vba excel-vba

Sub multiple()

    Workbooks("A.xlsx").Activate
    lastRow11 = Range("I" & Rows.Count).End(xlUp).Row

    For i = lastRow11 To 1 Step -1

        If i <> "" Then

            Value = Workbooks("A.xlsx").Worksheets(1).Cells(i, "I").Value
            Workbooks("B.xlsx").Activate
            Worksheets(1).Select

            Set DynRange = Selection.Find(What:=Value, LookIn:=xlFormulas, _
          LookAt:=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
          MatchCase:=False, SearchFormat:=False)

            If DynRange Is Nothing Then
                 MsgBox ("No codes found")
            Else
                cell.EntireRow.Copy
                Workbooks.Add
                ActiveSheet.Paste
            End If
        End If
    Next i
End Sub

在上面提到的代码中,我试图在工作簿B中搜索"DynRange"值(每次都是动态的)。目的是复制特定列具有这些值的行。工作簿B的工作表并将其粘贴到新工作簿中。 如果工作表B有5个工作表,则新工作簿应分别有5个工作表。但是,必须根据"DynRange"值过滤这5个工作表中的数据。

此外,还有下一个"DynRange"值。应添加新工作簿,其余部分应相同。

如何优化执行此任务?我的代码没有按预期工作。

1 个答案:

答案 0 :(得分:0)

使用它来查找所有匹配项:

If DynRange Is Nothing Then
     MsgBox ("No codes found")
Endif
Do While Not DynRange Is Nothing
     'process here the recent hit
     Set Fnd = Selection.FindNext(DynRange)
Loop

如果我正确理解您的需求,您希望处理B.xlsx中的所有工作表,但您只需参考工作表(1)。 我会避免使用.Selection。 您也可以考虑Sheets.Add而不是Workbooks.Add