如果找到文本,则复制另一个工作表中同一行的特定单元格

时间:2018-02-14 16:05:28

标签: excel vba excel-vba

如果确定的Text出现在“H”列中,我需要将一行的特定单元格复制到同一块中的另一个工作表。我已经能够复制整个列,但是我无法复制我真正想要的行的单元格。

Dim rango As Range
Dim i As Integer
Dim Source As Worksheet
Dim Target As Worksheet

Set Source = ActiveWorkbook.Worksheets("Sumas y Saldos")
Set Target = ActiveWorkbook.Worksheets("Check")

nfil = Source.Range("H9").End(xlDown).Row
i = 9
For Each rango In Source.Range("H8:H" & nfil)
    If rango = "REVISAR" Then
       Source.Rows(rango.Row).Copy Target.Rows(i)
       i = i + 1
    End If
Next rango
'2 second try of the code, this is what I try to do in the If to copy just that cells.
If rango = "REVISAR" Then
Source.Rows(rango.Column).Copy Target.Column(i)
Source.Range("G9:G" & nfil).Copy Destination:=Target.Range("A8:A" & nfil)
Source.Range("H9:H" & nfil).Copy Destination:=Target.Range("B8:B" & nfil)
Source.Range("I9:I" & nfil).Copy Destination:=Target.Range("C8:C" & nfil)
Source.Range("J9:J" & nfil).Copy Destination:=Target.Range("D8:D" & nfil)
Source.Range("K9:K" & nfil).Copy Destination:=Target.Range("E8:E" & nfil)
Source.Rows(rango.Row).Copy Target.Rows(i)
i = i + 1
End If

希望有人可以帮助我......谢谢

1 个答案:

答案 0 :(得分:0)

您可以使用AutoFilter()对象的Range方法,如下所示(未经测试,评论中的解释):

Option Explicit

Sub main()
    Dim Target As Worksheet

    Set Target = ActiveWorkbook.Worksheets("Check")

    With ActiveWorkbook.Worksheets("Sumas y Saldos")
        With .Range("G8:K" & .Cells(.Rows.Count, "H").End(xlUp).Row) 'reference its columns G:K cells from row 8 down to last not empty one in column "H"
            .AutoFilter field:=2, Criteria1:="REVISAR" ' filter referenced cells on 2nd column "REVISAR" content
            If Application.WorksheetFunction.Subtotal(103, .Columns(2)) > 0 Then .SpecialCells(xlCellTypeVisible).Copy Destination:=Target.Range("A8:D8")              ' if any filtered cell then get their underlying cells
        End With
        .AutoFilterMode = False
    End With
End Sub