查找匹配的复合数据并使用宏替换

时间:2016-08-02 07:25:17

标签: excel vba macros

我有一个场景,我必须在工作表1中查找两列并在工作表2中搜索匹配项,如果找到任何匹配的列,则替换该值。

Workshhet1

Worksheet2

目前我已经修复了在一列中找到匹配项。这是我的代码

export class Post{

   post:Post;

   @Input()
   set data(data:any) {
     this.post = new Post(data); 
     this.lightboxImages(this.post.content());
   }

   lightboxImages(content:any){
       let images = content. ???
       console.log(images);
   }
}

我想搜索专栏" A"和" D"在工作表1中反对列" A" &安培; " B"在工作表2中 我在SO搜索但没有看到任何类似于我的要求的帖子。任何人都可以帮助我。

谢谢!

1 个答案:

答案 0 :(得分:0)

这应该这样做。

 Sub FindMatch()

    Dim WS_one As Worksheet
    Dim WS_two As Worksheet

    Set WS_one = Worksheets("Sheet1")
    Set WS_two = Worksheets("Sheet2")
    ' Set worksheets to be used.

    Set lastCell = WS_one.Range("A:A").Find _
        ("*", after:=Cells(1, 1), SearchDirection:=xlPrevious)
    'set lastCell as last cell with any value
    For x = 1 To lastCell.Row
    'Set For loop to run until last cell with value.

        With WS_one
            'with sheet one only
            .Select
            Col_ValueA = .Cells(x, 1).Value
            Col_ValueD = .Cells(x, 4).Value
            'define value to search for
        End With

        With WS_two
            'with sheet two only
            .Select

            Set findvalue = .Range("A:A").Find _
                (Col_ValueA, after:=Cells(1, 1))
            'find 1st value equal to column A value

            Do
            'Do while no match found, and still values to check

                If Not findvalue Is Nothing Then
                    'if value exist then check for match

                    If .Cells(findvalue.Row, 2).Value = Col_ValueD Then
                        'check double match
                        ReplaceValue = .Cells(findvalue.Row, 3).Value
                        Exit Do
                    Else
                        'if second value doesn't match find new Column A value
                        temp = findvalue.Row
                        'security check

                        Set findvalue = .Range("A:A").Find _
                            (Col_ValueA, after:=Cells(temp, 1))
                        'find new row

                        If temp = findvalue.Row Then
                        'if row doesnt change exit do
                            Exit Do
                        End If
                    End If
                Else
                    'if no column A match found exit do
                    Exit Do
                End If

            Loop
        End With

        If Not ReplaceValue = "" Then
            ' replacement exists paste in column E and reset replacement value
            WS_one.Cells(x, 5).Value = ReplaceValue
            ReplaceValue = ""
        End If
   Next
   WS_one.Select

End Sub

本质上,代码将第一张的A列与第二张相匹配,如果该值匹配,我们检查第二个值。顺便说一句,您可能会注意到我发布的代码不再具有选择范围和活动单元格,尽量不要经常使用它们,因为它们不是很安全并且往往会使代码变慢。