VLOOKUP to compare data in 2 different workbooks with VBA

杀马特。学长 韩版系。学妹 提交于 2019-12-06 16:19:23

问题


I am somewhat new to VBA/Excel, so I was wondering if someone would help me out.

My question:
I have two different workbooks but in these workbooks two of the columns have common data. Thus I wanted to use VLOOKUP to compare the two columns and see if there are common data.

Details:
1st workbook : has 3 different sheets, I only need to use the sheet "Items" which has the data in column 2.

2nd workbook: has only 1 sheet called "Data" and has data in column 4.

Thus my goal is to compare the 2 columns. In workbook1 there is an empty column next to the data column so, if there is a match I want to say "ok" in it. If no match then "".

I tried VLOOKUP but really could not understand it. Plus this is for work.


回答1:


You may try this..

Assuming the name of your second workbook is Book2.xlsx, then try this...

On First workbook In C2

=IF(ISNUMBER(MATCH(B2,'[Book2.xlsx]Data'!$D:$D,0)),"OK","")

and copy it down.

If you require a VBA solution, one approach to get the desired output is as below... The following code assumes that both the Book1.xlsm (which will contain the below code) and Book2.xlsx are saved in the same folder. If they are saved at different location, change the path and name of Book2.xlsx in the following lines of code.

sourceFilePath = dwb.Path & "\"
sourceFileName = "Book2.xlsx"

Code:

Sub CompareData()
Dim swb As Workbook, dwb As Workbook
Dim sws As Worksheet, dws As Worksheet
Dim slr As Long, dlr As Long, i As Long
Dim sourceFilePath As String, sourceFileName As String
Dim x, y, z, dict
Application.ScreenUpdating = False

Set dwb = ThisWorkbook
Set dws = dwb.Sheets("Items")
dlr = dws.Cells(Rows.Count, 2).End(xlUp).Row
x = dws.Range("B2:B" & dlr).Value
ReDim z(1 To dlr)
sourceFilePath = dwb.Path & "\"
sourceFileName = "Book2.xlsx"

Workbooks.Open sourceFilePath & sourceFileName

Set swb = ActiveWorkbook
Set sws = swb.Sheets("Data")
slr = sws.Cells(Rows.Count, 4).End(xlUp).Row
y = sws.Range("D2:D" & slr).Value

Set dict = CreateObject("Scripting.Dictionary")

For i = 1 To UBound(y, 1)
    dict.Item(y(i, 1)) = ""
Next i
swb.Close False

For i = 1 To UBound(x, 1)
    If dict.exists(x(i, 1)) Then
        z(i) = "OK"
    Else
        z(i) = ""
    End If
Next i
dws.Range("C2").Resize(UBound(x, 1), 1).Value = Application.Transpose(z)
Application.ScreenUpdating = True
End Sub


来源:https://stackoverflow.com/questions/43221414/vlookup-to-compare-data-in-2-different-workbooks-with-vba

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!