我的工作簿中有两张纸。两者都有相同的列,但顺序不同。我需要将所有行从一张纸复制到另一张。
是否可以在匹配的列名下精确复制数据?两张纸都有CZ的列。
答案 0 :(得分: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