在excel工作簿中从一个工作表搜索值到另一个工作表

时间:2016-06-12 10:42:33

标签: excel vba

我在Excel中有两张纸。我想确定sheet2中是否存在sheet1的值。以下代码不会在我的文件中产生任何输出或错误。

Sub t()
    For i = 2 To 48
        For j = 2 To 48
            If Worksheets("Operator PC").Cells(i, 1).Value = Worksheets("PC Locations").Cells(j, 1).Value Then
                MsgBox "Value"
            End If
        Next j
    Next i
End Sub

2 个答案:

答案 0 :(得分:0)

你可以这样做:

Sub t()
    Dim rFirst As Range
        Set rFirst = Worksheets("Sheet1").Range("A1").CurrentRegion
    Dim rSecond As Range
        Set rSecond = Worksheets("Sheet2").Range("A1").CurrentRegion
    Dim rFound As Range
    Dim rCell As Range

    For Each rCell In rFirst
        Set rFound = rSecond.Find(rCell, lookat:=xlWhole)
        If Not rFound Is Nothing Then MsgBox (rCell.Value)
    Next rCell
End Sub

如果工作表非常大,最好先使用变量而不是范围变量将范围加载到内存中。

答案 1 :(得分:0)

将SQL解决方案视为Excel(假设PC版本)可以使用Windows Jet / ACE SQL引擎在包括当前文件的工作簿上运行查询。在这里,您可以避免使用嵌套的For循环和if / then逻辑,甚至可以扩展以匹配其他列或各种WHERE条件。

下面在两个工作表之间运行内部联接查询,并将结果输出到名为 Matches 的现有工作表。请务必使用实际的第1列标题更改strSQL中的 ColA 。驱动程序和提供程序类型包含两个连接字符串。

Sub RunSQL() 
   Dim conn As Object, rst As Object 
   Dim strConnection As String, strSQL As String
   Dim LastRow As Integer

   Set conn = CreateObject("ADODB.Connection") 
   Set rst = CreateObject("ADODB.Recordset")

   ' Specify full workbook path
   ' strConnection = "DRIVER={Microsoft Excel Driver (*.xls, *.xlsx, *.xlsm, *.xlsb)};" _ 
   '                  & "DBQ=C:\Path\To\Workbook.xlsm;" 
   strConnection = "Provider=Microsoft.ACE.OLEDB.12.0;" _ 
                    & "Data Source='C:\Path\To\Workbook.xlsm';" _ 
                    & "Extended Properties=""Excel 8.0;HDR=YES;"";"

   ' OPEN DB CONNECTION 
   conn.Open strConnection

   strSQL = " SELECT o.ColA FROM ['Operator PC'$] o" _ 
              & " INNER JOIN ['PC Location'$] p" _ 
              & " ON o.ColA = p.ColA"

   ' OPEN QUERY RECORDSET 
   rst.Open strSQL, conn

   ' COPY DATA TO WORKSHEET 
   LastRow = Worksheets("Matches").Cells(Worksheets("Matches") _ 
             .Rows.Count, "A").End(xlUp).Row 
   Worksheets("Matches").Range("A" & LastRow + 1).CopyFromRecordset rst 

   rst.Close
   conn.Close

End Sub