VBA基于参考单元格中的匹配值将数据从一个范围移动到另一个工作表范围

时间:2013-11-25 19:53:46

标签: excel vba

在表1上我有一个A1值,我在A5中有一个表:A11,B5:B11。

A5:A11是与sheet2 B1:G1相匹配的标题。答:A是A1的匹配值列表。

B5:B11是我想要将sheet2移动到其列中的值,其标题与A5匹配:在Sheet2上的行中的A11,其A列中的值为A1:A。

以下是一些以前建议的代码,但它不起作用,但我认为它接近于工作。

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

1 个答案:

答案 0 :(得分:0)

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