excel 将下一字行从工作表复制到另一工作表

s4chpxco  于 2023-01-10  发布在  其他
关注(0)|答案(1)|浏览(173)

我得到的代码找到所有包含特定单词的行,然后将其发送到另一个工作表,它工作正常,但我面临一个问题,我想复制找到的单词的下一行,然后将其粘贴到下一个工作表的下一列。
代码:

Option Explicit

Sub SearchForString()

    Dim a As Long, arr As Variant, fnd As Range, cpy As Range, addr As String

    On Error GoTo Err_Execute

    'populate the array for the outer loop
    arr = Array("Water", "Fighter", "Demon")

    With Worksheets("Data")

        'outer loop through the array
        For a = LBound(arr) To UBound(arr)
            'locate first instance
            Set fnd = .Columns("A").Find(what:=arr(a), LookIn:=xlFormulas, LookAt:=xlPart, _
                                         SearchOrder:=xlByRows, SearchDirection:=xlNext, _
                                         MatchCase:=False, SearchFormat:=False)
            If Not fnd Is Nothing Then
               'record address of first find
                addr = fnd.Address
                'seed the cpy range object
                If cpy Is Nothing Then Set cpy = fnd.EntireRow
                Do
                    'build union
                    Set cpy = Union(cpy, fnd.EntireRow)

                    'look for another
                    Set fnd = .Columns("A").FindNext(after:=fnd)

                'keep finding new matches until it loops back to the first
                Loop Until fnd.Address = addr
            End If
        Next a

    End With

    With Worksheets("sheet19")
        'one stop copy & paste operation
        cpy.Copy Destination:=.Cells(.Rows.Count, "A").End(xlUp).Offset(1, 0)
    End With

    MsgBox "All matching data has been copied."

    Exit Sub

Err_Execute:
    Debug.Print Now & " " & Err.Number & " - " & Err.Description

End Sub

以下是图片示例

我试着用. copy. offset(1)但是它不起作用,所以我试着在这里问可能有人有一个解决方案。

wfveoks0

wfveoks01#

不要在一行中查找和粘贴数据,而是将其分为两行,以便可以复制偏移并粘贴到偏移。

With Worksheets("sheet19")
    Dim dst As Range
    Set dst = .Cells(.Rows.Count, "A").End(xlUp).Offset(1, 0)
End With

cpy.Copy Destination:=dst
cpy.Offset(1) Destination:=dst.Offset(0, 1)

相关问题