【问题标题】:Copy Data from One Sheet to Another Sheet by Matching Column Names通过匹配列名将数据从一个工作表复制到另一个工作表
【发布时间】:2012-09-21 19:05:44
【问题描述】:

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

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

【问题讨论】:

    标签: excel excel-2010


    【解决方案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-11-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-07-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-08-23
      相关资源
      最近更新 更多