遍历列中的所有单元格,如果找到匹配项,则复制并粘贴文本

时间:2019-08-15 15:25:59

标签: excel vba for-loop copy-paste with-statement

我正在努力完成一个简单的任务。该代码当前有效:

With ActiveSheet
    Set criteriarange = Range("A1:A" & LShtRow)
        For Each criteriacell In criteriarange
            If Not criteriacell.Value Like "tag:*" Then
                criteriacell.ClearContents
            End If
        Next criteriacell
        For row = LShtRow To 1 Step -1
            With .Cells(row, "B")
                If IsError(Application.Match(.Value, ArrDataNames, 0)) Then .ClearContents
            End With
        Next row
End With

我需要遍历这些相同的单元格,并寻找我所谓的“异常”。我将这些异常放入数组中。当前该数组只有一个例外,它是“ FM”,如果它在列“ B”的第i行中找到“ FM”,那么我想从列“ E”的第i行复制文本并将其粘贴到列“ H”的行一世。这是我一直在尝试的内容,但它表示“类型不匹配”。我敢肯定这是一些简单的语法,但是我尝试了一些事情并且无法弄清楚。这是我的代码:

Dim ArrExceptions As Variant
ArrExceptions = Array("FM")

With ActiveSheet
    Set criteriarange = Range("A1:A" & LShtRow)
        For Each criteriacell In criteriarange
            If Not criteriacell.Value Like "tag:*" Then
                criteriacell.ClearContents
            End If
        Next criteriacell
        For row = LShtRow To 1 Step -1
            With .Cells(row, "B")
                If IsError(Application.Match(.Value, ArrDataNames, 0)) Then .ClearContents
            End With
        Next row
'New Code'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
        For row = LShtRow To 1 Step -1
                If Application.Match(.Cells(row, "B").Value, ArrExceptions, 0) Then .Range(.Cells(row, "E")).Copy .Range(.Cells(row, "H"))
        Next row
End With

1 个答案:

答案 0 :(得分:0)

With ActiveSheet
    Set criteriarange = Range("A1:A" & LShtRow)
        For Each criteriacell In criteriarange
            If Not criteriacell.Value Like "tag:*" Then
                criteriacell.ClearContents
            End If
        Next criteriacell
        For row = LShtRow To 1 Step -1
            With .Cells(row, "B")
                If IsError(Application.Match(.Value, ArrDataNames, 0)) Then .ClearContents
            End With
        Next row
        For row = LShtRow To 1 Step -1
                If Not IsError(Application.Match(.Cells(row, "B").Value, ArrExceptions, 0)) Then .Cells(row, "E").Copy .Cells(row, "H")
        Next row
End With