合并两张纸

时间:2018-03-14 11:53:05

标签: excel vba excel-vba vlookup

我有两张不同的表格(Tabelle2& Tabelle3),我想根据登记号码将它们合并为第三张(Tabelle1)。

要将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

在2.步骤中我希望我的代码检查“注册号”在Tabelle1中,只复制从Tabelle3到Tabelle1的那些行。 注意:Tabelle3包含更多“注册号”哪些数据我不需要

有谁知道使用哪种功能或如何解决这种挑战? :)

enter image description here

2 个答案:

答案 0 :(得分:0)

试试这个

    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

答案 1 :(得分:0)

让它变得非常简单 - 将三个表放在同一个工作表上:

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后,第二个值将写入找到的值
  • 的偏移量
  • 同样适用于Shoe Sizes表