0

我的工作簿中有两张纸。两者都有相同的列,但顺序不同。我需要将所有行从一张纸复制到另一张纸。

有什么方法可以在匹配的列名下精确复制数据?两张纸的列最高为 CZ。

4

1 回答 1

1

您需要执行 VB Editor Menu/Tools/References 并选中 Microsoft Scripting Runtime 旁边的框。这使您可以访问 Scripting.Dictionary,它是一个键控散列对象(键/值对)

Sub CopyByCol()

Dim lCol As Long, lCols As Long, sCol As String, lRows As Long
Dim dictCol As New Scripting.Dictionary
Dim rFrom As Range, rTo As Range

    Set rFrom = Sheet1.Range("A1")
    Set rTo = Sheet2.Range("A1")

' Store hash of where column names occur in target sheet, keyed by Col name
    lCols = rFrom.Offset(0, 255).End(xlToLeft).Column - rFrom.Column
    For lCol = 0 To lCols
        sCol = rTo.Offset(0, lCol).Value
        dictCol.Add sCol, lCol
    Next

' Get key column name from From sheet, and write to correct col in To sheet
    For lCol = 0 To lCols
        sCol = rFrom.Offset(0, lCol).Value
        lRows = rFrom.Offset(65000, lCol).End(xlUp).Row - rFrom.Row
        Range(rFrom.Offset(1, lCol), rFrom.Offset(lRows, lCol)).Copy Destination:=rTo.Offset(1, dictCol(sCol))
    Next

End Sub
于 2012-09-21T11:05:44.577 回答