使用"喜欢"查找单元格是否包含值?

时间:2016-06-30 18:27:33

标签: excel vba

我正在尝试将一个工作簿中的每个单元格的值与另一个的值进行比较,如果它们的值匹配我希望将整个行复制到第一个工作簿。

我将N设置为Im比较和使用" If(cell.Value Like" N")= True然后"

问题:正在发挥作用,它找到所有具有字母" N"在其中并将其复制。我需要它来查找具有我之前分配给N的值的所有单元格。我的代码如下。

Option Explicit

Sub Compare()

Dim N as String

For i = 1 To Workbook(1).Worksheets(1).UsedRange.Rows.Count

        N = Workbook(1).Worksheets(1).Cells(i, 4).Value

        For Each cell In Workbook(2).Sheets(2).Range("B:B").Cells
            If (cell.Value Like "*N*" Then) = True Then
                'Do something; ie, copy over row
            End If
        Next cell
Next i

Workbook(2).Close

End Sub()

1 个答案:

答案 0 :(得分:0)

尝试一下,看看它是否适合你:

Option Explicit

Sub Compare()

Dim wb1 As Workbook
Dim wb2 As Workbook

Set wb1 = Application.Workbooks("Book1")
Set wb2 = Application.Workbooks("Book2")

Dim wsName As String

wsName = "Sheet1"

Dim rng1 As Range
Dim rng2 As Range

wb1.Activate
Set rng1 = wb1.Worksheets(wsName).Range(Cells(1, 1), Cells(Rows.Count, 1).End(xlUp))
wb2.Activate
Set rng2 = wb2.Worksheets(wsName).Range(Cells(1, 1), Cells(Rows.Count, 1).End(xlUp))

Dim cell As Range
Dim found As Range

For Each cell In rng1
    Set found = rng2.Find(cell, LookIn:=xlValues, LookAt:=xlPart,  SearchOrder:=xlByColumns, SearchDirection:=xlNext, MatchCase:=False)
    If Not found Is Nothing Then
        'Copy over row
    End If
Next cell

wb2.Close

End Sub