2017-06-12 201 views
0

我设法遍历两列来查找一列中的值是否出现在另一列中。VBA excel,在列中找到对应的值

现在下一步是确定两列中的值是否在值的右侧的单元格中包含相同的值。

所需结果和当前结果的图片应解释我想实现的目标。

P.S.不要被代码弄糊涂,因为我的工作簿中的列位于两张不同的工作表上。

enter image description here

我曾尝试通过循环列两次,一旦我得到一个匹配的确认,但在这一点上,我只是失去了....对不起

Sub loopDb() 

    Set dbsheet1 = ThisWorkbook.Sheets("Sheet1") 
    Set dbsheet2 = ThisWorkbook.Sheets("Sheet2") 

    lr1 = dbsheet1.Cells(Rows.Count, 1).End(xlUp).Row 
    lr2 = dbsheet2.Cells(Rows.Count, 1).End(xlUp).Row 

    For x = 2 To lr1 
     act1 = dbsheet1.Cells(x, 1) 

     For y = 2 To lr2 
      act2 = dbsheet2.Cells(y, 1) 

      If Not dbsheet2.Cells(y, 3).Value = "Match" Then 
       'Only compare if previoulsy not done or resulted in "No match" 
       If act2 = act1 Then 
        dbsheet2.Cells(y, 3).Value = "Match" 

        If dbsheet2.Cells(y, 3).Value = "Match" Then 
         For i = 2 To lr1 
          If dbsheet2.Cells(y, 1).Value = dbsheet2.Cells(i, 1).Value Then 
           dbsheet2.Cells(y, 4).Value = "Match" 
          Else 
           dbsheet2.Cells(y, 4).Value = "No match" 
          End If 
         Next i 
        End If 

       Else 
       dbsheet2.Cells(y, 3).Value = "No match" 
       End If 
      End If 
     Next y 

    Next x 


End Sub 
+0

为什么不使用'application.worksheetfunction.match(col1value,col2,0)'和'和'在你的逻辑,所以'如果MATCH1和MATCH2 then' –

回答

2

由于Nathan_Sav指出,你可以用比赛公式解决你的问题。

MATCH formula让你工作完全没有vba。

式匹配col1和COL2:

=IFERROR(IF(MATCH(sheet1!A1;sheet2!$A$1:$A$10;0)>=0;"Match");"No match") 

匹配公式返回其中发现匹配的索引。否则会出错。要获得“匹配”和“不匹配”这两个词,我们需要IFIFERROR公式。

式两种COL1 & VAL1的匹配和COL2 & VAL 2

{=IFERROR(IF(MATCH(sheet1!A1&sheet1!B1;sheet2!$A$1:$A$10&sheet2!$B$1:$B$10;0)>=0;"Match");"No match")} 

Sheet 2中的两列组合使得使用必要的阵列式的。为了使其工作,请按Ctrl + Shift + Enter。

我希望这有助于