在另一个工作簿中的另一个工作表中共有的工作表中查找ID

时间:2015-08-13 02:49:13

标签: excel vba excel-vba

我有两个工作簿,包含两个不同工作表中的公共项目ID。我创建了一个代码,允许程序在一个工作表中搜索唯一ID,从该行检索与该id相关的信息,然后粘贴到该对应项目ID的行,到另一个工作簿中的另一个工作表。这段代码可以工作,但只能在假设两个列表的顺序完全相同的情况下工作,而实际上它们是混乱的。所以我需要帮助在代码中包含查找功能,它在一个工作簿表中找到项目ID,检索行信息并将其粘贴到另一个工作簿表。

{{1}}

1 个答案:

答案 0 :(得分:1)

下面的内容应该匹配它们,无论ID在哪个顺序,你必须使用两个数组。它复制列B,假设ID在A列中,请继续添加您要复制的许多列。请参阅下文并尝试使用您自己的代码。 UNTESTED。

Dim fpath As String
Dim owb As Workbook



fpath = "change to the location of workbook you want to paste to"


Set owb = Application.Workbooks.Open(fpath) 'opens workbook

Dim Master As Worksheet 'your current book
Dim Slave As Worksheet 'one your pasting too

'please verify if the master and slave are correct here
Set Slave = owb.Worksheets("name of sheet in one your pasting too")
Set Master = ThisWorkbook.Worksheets("name of sheet in book you are in")

For i = 1 To 1000 '(the slave sheet)
For j = 1 To 1000 '(the master sheet)

If Master.Cells(j, 1).Value = "" Then ExitFor   


   If Master.Cells(j, 1).Value = Slave.Cells(i, 1).Value Then 'assuming both Id's are in column A
       Slave.Cells(i, 2).Value = Master.Cells(j, 2).Value 'this will copy column B, continue to add for each column you want copying e.g. add another with "3" and "4" etc.

  End If
End If

Next
Next


MsgBox ("Data Transfer Successful")