如何将一个工作表列数据与另一工作表进行匹配?

时间:2018-07-23 17:51:43

标签: vba

我有2个工作簿,我想将1个工作簿的工作表与另一列的工作簿2工作表进行匹配,如果2个单元格具有相同的匹配ID,则返回标题。

例如: 如果我的“ X”标记的ID全部与Workbook-1 ID匹配,我想返回Workbook-2标头,如A001,例如A001。

预期结果,如工作簿2中的“输出”表

Workbook-1

workbook-2

结果示例

1 个答案:

答案 0 :(得分:0)

我对此不屑一顾,尽管这对我没有多大意义。它要求您使用的三个工作表使用屏幕快照中的确切工作表名称,并且没有其他工作表共享该名称。我没有测试,但是

Sub WhatTheHeckisThis()
Dim WKBK As Workbook, wsStart As Worksheet, wsLookup As Worksheet, wsOutput As Worksheet
Dim lineLookup As Range, i As Long, yCell As Range, rCell As Range


Dim tWSstart As String: tWSstart = "Datasheet"
Dim tWSLookup As String: tWSLookup = "MATCH"
Dim twsOutput As String: twsOutput = "OUTPUT"

For Each WKBK In Application.Workbooks
    For Each WS In WKBK.Sheets
        If UCase(WS.Name) = UCase(tWSstart) Then
            Set wsStart = WS
        ElseIf UCase(WS.Name) = (tWSLookup) Then
            Set wsLookup = WS

        ElseIf UCase(WS.Name) = UCase(twsOutput) Then
            Set wsOutput = WS
        End If
    Next WS
Next WKBK


For Each rCell In Intersect(wsStart.Range("B2:B" & Rows.Count), wsStart.UsedRange).Cells

    Set lineLookup = Nothing
    Set lineLookup = wsLookup.Cells.Find(rCell.Value, _
        After:=wsLookup.Cells.Cells(1, 1), _
        LookIn:=xlFormulas, _
        LookAt:=xlPart, _
        SearchOrder:=xlByRows, _
        SearchDirection:=xlNext, _
        MatchCase:=False, _
        SearchFormat:=False)

    If Not lineLookup Is Nothing Then

        For Each yCell In Intersect(lineLookup.EntireRow, wsLookup.UsedRange).Cells

            If UCase(yCell.Value) = "X" Then
                With wsOutput
                i = .Cells(Rows.Count, 1).End(xlUp).Row + 1
                 .Cells(i, 1).Value = i - 1
                .Cells(i, 2).Value = wsLookup.Cells(1, yCell.Column).Value
                End With

            End If
        Next yCell
    End If

Next rCell

End Sub