简体   繁体   中英

Excel VBA - Copy and paste a range of cells when certain names match from one work book another

I am working on a project and I have got a point where I want to copy certain data from one sheet to another. Eg if in column "A" a cell contains "Hello" then copy what is in cell "E4". Would an "IF" statement would work?

The code I have so far for my project is

Sub testfortito()
    Dim x As Workbook
    Dim y As Workbook
    Dim ws As Worksheet

    'this opens both workbooks
    Set x = Workbooks.Open("Location1")
    Set y = Workbooks.Open("Location2")

    'to do the copy
    x.Sheets("sheet3").Range("A2:AC2").Copy

    For Each ws In Worksheets
        If ws.Name <> "sheet3" Then
            ws.Range("E3").Copy
            Worksheets ("Sheet3")
        End If    
    Next ws
End Sub

Try this

Sub testfortito()
    Dim colEtxt(), ctr

    ctr = 0
    With Sheet1.Range("A:A")
        Set txt = .Find(What:="hello", LookIn:=xlValues, LookAt:=xlPart, SearchOrder:=xlByRows, _
        SearchDirection:=xlNext, MatchCase:=False, SearchFormat:=False)
        If Not txt Is Nothing Then
            firstAddress = txt.Address
            Do
                ReDim Preserve colEtxt(ctr)
                colEtxt(ctr) = Range(txt.Address).Offset(0, 4).Value
                Set txt = .FindNext(txt)
                ctr = ctr + 1
            Loop While Not txt Is Nothing And txt.Address <> firstAddress
        End If
    End With

    'copy the array onto sheet2 using transpose technique
    Sheet2.Range("A1:A" & UBound(colEtxt) + 1) = WorksheetFunction.Transpose(colEtxt)
End Sub

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM