Excel宏可以在工作表中找到一个单元格,然后将整个行复制到另一个工作表中

问题描述 投票:-1回答:1

我有一个具有约50k行的excel工作表,我需要一个宏来搜索该工作表中的单元格,如果它找到将整个行复制到另一工作表中的单元格,我的问题是该关键字可能在多行上,因此如果有4个带有该关键字的单元格,我需要它复制所有4行并将它们粘贴到另一张纸中

Sub saca()

Dim intPasteRow As Integer
intPasteRow = 2
Dim ceva As Range
Dim FirstAddress As String
Dim intRow As Integer

Sheets("Sheet2").Select
Columns("A:AV").Select
On Error Resume Next
Set ceva = Selection.Find(What:="m762", After:=ActiveCell, LookIn:= _
    xlFormulas, LookAt:=xlWhole, SearchOrder:=xlByRows, SearchDirection:= _
    xlNext, MatchCase:=True, SearchFormat:=True).Activate
If Not ceva Is Nothing Then
    FirstAddress = ceva.Address
    Do
        Set ceva = Selection.FindNext(ceva).Activate
    Loop While Not ceva Is Nothing And ceva.Address <> FirstAddress
End If

intRow = ActiveCell.Row
Rows(intRow & ":" & intRow).Select
Selection.Copy

Sheets("Sheet1").Select
ActiveSheet.Paste

End Sub

到目前为止,它在Sheet2中搜索“ m762”,但是它只复制带有“ m762”单元格的第一行,而不是全部选择它们...我找不到找到使其选择带有“ m762”的所有行的方法。 “在其中

excel vba
1个回答
0
投票

虽然不是最好或最快的解决方案,但这是一个基本的For Loop宏,它将循环遍历每个单元格,当找到条件时,它将通过以下方式将Sheet2中的行复制到Sheet1中的下一个空行:将值直接从Sheet2设置为Sheet1。然后它将继续并复制找到条件的每一行。

Dim cel As Range, lRow As Long

    For Each cel In ThisWorkbook.Sheets("Sheet2").Range("A2:AV" & Sheets("Sheet2").Cells(Rows.Count, 1).End(xlUp).Row)
        If cel.Value = "m762" Then
            lRow = ThisWorkbook.Sheets("Sheet1").Cells(Rows.Count, 1).End(xlUp).Row

            ThisWorkbook.Sheets("Sheet1").Cells(lRow + 1, 1).Resize(, 48).Value = ThisWorkbook.Sheets("Sheet2").Cells(cel.Row, 1).Resize(, 48).Value
        End If
    Next cel 
© www.soinside.com 2019 - 2024. All rights reserved.