简体   繁体   中英

VBA move data from one range to another sheet range based on matching values in reference cell

On sheet 1 I have a value in A1, I have a table in A5:A11,B5:B11.

A5:A11 are headers that match sheet2 B1:G1. A:A is the list of matching values for A1.

B5:B11 are values I want moved to sheet2 into their columns with headers that match A5:A11 in the row on sheet2 that has the value from A1 in its column A:A.

Here is some previously suggested code to do it, however it is not functional but I think its close to working.

Sub moveData()
    Dim rS As Range
    Dim rT As Range
    Dim Cel As Range
    Dim lRow As Long

    With Sheet1
        lRow = .Range("a1").Value
        Set rS = .Range("A5", .Cells(.Rows.CountLarge, 1).End(xlUp)) 'source headings
    End With
    With Sheet2
        Set rT = .Range("A1", .Cells(1, .Columns.Count).End(xlToLeft)) 'target headings
    End With

    'find matching heading Sheet2, copy data to specified row
    On Error Resume Next 'skip over non-matches
    For Each Cel In rS
        Sheet2.Cells(lRow, rT(Application.Match(Cel.Value, rT, 0)).Column).Value = Cel.Offset(, 1).Value
    Next Cel
End Sub
Sub tgr()

    Dim ws1 As Worksheet
    Dim ws2 As Worksheet
    Dim VisCell As Range
    Dim lCalc As XlCalculation

    Set ws1 = Sheets("Sheet1")
    Set ws2 = Sheets("Sheet2")

    With Application
        lCalc = .Calculation
        .Calculation = xlCalculationManual
        .ScreenUpdating = False
        .EnableEvents = False
    End With

    With Intersect(ws2.UsedRange, ws2.Columns("A"))
        .AutoFilter 1, ws1.Range("A1").Text
        On Error Resume Next
        For Each VisCell In .Offset(1).Resize(.Rows.Count - 1).SpecialCells(xlCellTypeVisible).Cells
            ws1.Range("B5:B11").Copy
            VisCell.Offset(, 1).PasteSpecial xlPasteValues, Transpose:=True
        Next VisCell
        On Error GoTo 0
        .AutoFilter
    End With

    With Application
        .Calculation = lCalc
        .ScreenUpdating = True
        .EnableEvents = True
    End With

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