Comparing two columns in one Excel sheet, to two columns in another sheet, and if they match, copy data from another column

时间:2018-01-23 19:26:32

标签: excel vba

I've been looking at using the Excel VLOOKUP function to accomplish this, but I'm pretty unfamiliar with it.

I need to do the following:

On sheet one, column A and column B contain 3000 rows of first names and last names.

I need to compare this to a second sheet that also has first names and last names, with a third column containing email addresses.

If the two columns are an exact match on sheet 1 and sheet 2(e.g. A1+B1 = Sheet2 A7+B7), I need to copy the email address from column C on sheet 2, to column C on sheet 1.

Is there a VLOOKUP formula to accomplish this, or is this going to need to be a VBA script?

4 个答案:

答案 0 :(得分:2)

试试这个:

将此公式放在sheet1列C:

=VLOOKUP(CONCAT(A1,B1),Sheet2!A:D,4,0)

你需要在sheet2上有4列,第一列需要像这样的CONCATENATE FORMULA:

=CONCAT(B1,C1)

第二列是您的名字,第三列是您的姓氏,最后一列是相应的电子邮件。

这个公式如何运作?

 =VLOOKUP(**CONCAT(A1,B1)**,Sheet2!A:D,4,0)

它连接了sheet1上的名字和姓氏,并在A列的Sheet2上查找它,如果匹配,它将返回sheet2列D中的电子邮件单元格值(列D索引为4)。

希望这能帮到你

答案 1 :(得分:1)

I would suggest a VBA script that uses an SQL query, maybe something like this (you need some SQL language skills in order to get the right result). Anyways, this is the approach I would recommend for an advanced user:

Dim oConn As ADODB.Connection, rs As ADODB.Recordset

sWorkbookName = ThisWorkbook.FullName
connString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=""" & 
sWorkbookName & """;Extended Properties=""Excel 12.0 Xml;HDR=YES;IMEX = 1"""

sSheet1="myDataSheet1"
sSheet2="myDataSheet2"
oConn.Open connString
'just an example of SQL, you have to customize it
sSQL = "SELECT [FIRST NAME], [LAST NAME],[EMAIL] FROM [" & sSheet2 & "$] " & 
" WHERE 
[FIRST NAME] + [LAST NAME} IN (SELECT [FIRST NAME] + [LAST NAME] FROM [" & sSheet1 & "$]" & ")  ORDER BY [FIRST NAME] ASC"

rs.Open sSQL, oConn, adOpenStatic, adLockOptimistic, adCmdText

'dump results on a temporary sheet 
ThisWorkbook.Worksheets("tmp_sheet").Range("A2").CopyFromRecordset rs

rs.Close
oConn.Close  

答案 2 :(得分:1)

您可以输入=INDEX(Sheet2!C:C,SUMPRODUCT(--(Sheet2!A:A=A1),--(Sheet2!B:B=B1),ROW(Sheet2!C:C)),0)

SELECT to_char(student.dateInserted, 'YYYY-MM-DD'), count(student.dateInserted)
FROM STUDENTS student
INNER JOIN TEACHERS teacher ON (student.teacher_id == teacher.id)
WHERE (student.age > 20 AND student.dateInserted < SYSDATE)
OR (student.age < 20 AND student.dateUpdated  > SYSDATE-2)
GROUP BY to_char(student.dateInserted, 'YYYY-MM-DD')
ORDER BY to_char(student.dateInserted, 'YYYY-MM-DD');

然后向下复制。

这不需要:

  1. 使用VBA
  2. 使用数组公式
  3. 使用其他(帮助)列。
  4. 这一点的重要性超出了范围。

    更多详情

    您正在寻找的内容通常称为多重查找。 在SO中有很多关于它的问题,以及其他许多其他文章。 我已编制了here此类帖子的列表。

    有很多可能的解决方案。 我发现最健壮的那个here。 这就是我在目前的答案中使用的。

答案 3 :(得分:0)

=IF(AND(Sheet1.A1=Sheet2.A1, Sheet1.B1=Sheet2.B1),Sheet2.C1,'')

将此公式另存为目标工作表的C列。