代码之家  ›  专栏  ›  技术社区  ›  HPM

合并两张工作表

  •  0
  • HPM  · 技术社区  · 7 年前

    我有两个不同的表(表2和表3),我想根据注册号将它们合并到第三个表(表1)。

    要将Tabelle2复制到Tabelle1中的正确列中,我使用的是工作平稳的VLookup。

    Dim lastrow As Long
    lastrow = Tabelle2.Range("A" & Rows.Count).End(xlUp).Row
    Set myrange = Tabelle2.UsedRange
    
    
    For i = 2 To lastrow
        Tabelle1.Cells(i, 1) = Application.WorksheetFunction.VLookup(Tabelle2.Cells(i, 1), myrange, 1, False)
    Next i
    
     For i = 2 To lastrow
        Tabelle1.Cells(i, 2) = Application.WorksheetFunction.VLookup(Tabelle2.Cells(i, 1), myrange, 2, False)
    Next i
    
    For i = 2 To lastrow
        Tabelle1.Cells(i, 6) = Application.WorksheetFunction.VLookup(Tabelle2.Cells(i, 1), myrange, 3, False)
    Next i
    

    在a 2中。步骤我希望我的代码检查Tabelle1中的“寄存器号”,并仅将这些行从Tabelle3复制到Tabelle1。 注意:Tabelle3包含更多的“寄存器号”,我不需要这些数据

    有人知道使用哪个函数或如何解决这个难题吗?:)

    enter image description here

    2 回复  |  直到 7 年前
        1
  •  0
  •   Maddy    7 年前

    试试这个

        Dim lastrow As Long
        lastrow = Tabelle3.Range("A" & Rows.Count).End(xlUp).Row
        Set myrange = Tabelle3.UsedRange
    
    
        For i = 2 To lastrow
            Tabelle1.Cells(i, 3) = Application.WorksheetFunction.VLookup(Tabelle1.Cells(i, 1), myrange, 2, False)
        Next i
    
         For i = 2 To lastrow
            Tabelle1.Cells(i, 4) = Application.WorksheetFunction.VLookup(Tabelle1.Cells(i, 1), myrange, 3, False)
        Next i
    
        For i = 2 To lastrow
            Tabelle1.Cells(i, 5) = Application.WorksheetFunction.VLookup(Tabelle1.Cells(i, 1), myrange, 4, False)
        Next i
    
        2
  •  0
  •   Vityata    7 年前

    让我们让它变得非常简单-将三个表放在同一工作表上,如下所示:

    enter image description here

    我们的想法是,在运行以下代码后,得到类似的结果:

    enter image description here

    可能最简单的方法是通过一些糟糕的实践实现它,因为硬编码是这样的:

    Public Sub TestMe()
    
        Dim cnt             As Long
        Dim combinedIndex   As Range
        Dim currentCell     As Range
    
        With Worksheets(1)
            Set combinedIndex = .Range("A7:A12")
    
            'Fill table with names
            For cnt = 2 To 5
                Set currentCell = Nothing
                Set currentCell = combinedIndex.Find(Cells(cnt, 1))
                If Not currentCell Is Nothing Then
                    currentCell.Offset(0, 1) = .Cells(cnt, 2)
                End If
            Next cnt
    
            'Fill table with Shoe Sizes
            For cnt = 2 To 5
                Set currentCell = Nothing
                Set currentCell = combinedIndex.Find(Cells(cnt, 4))
                If Not currentCell Is Nothing Then
                    currentCell.Offset(0, 2) = .Cells(cnt, 5)
                End If
            Next cnt
        End With
    
    End Sub
    

    代码就是这样做的:

    • 定义 combinedIndex 范围在更一般的情况下 Worksheets(1).Range("A:A")
    • 然后用名称在表中循环。它是从2到5的硬编码,但可以稍微放宽一点。每年一次 RegisterN 则将第二个值写入找到的值的偏移量
    • 鞋码表也是如此