在IF-THEN语句中循环进行单元格比较

时间:2015-11-25 10:19:02

标签: excel vba

我需要将范围src.Range("A1:A" & 10)中的每个单元格与范围src3.Range("A1:A" & 3)中的单元格进行比较,并且仅当src单元格不等于任何src3单元格时才继续。如果我手动列出每个比较(作为评论 - 我最终得到的东西。它可以工作但是会有更大的比较范围)。但是当我尝试循环它时它不会。我无法将IFTHEN分开。而且我找不到替代方案。

  For temprow = 1 To rngSelectionTable.Rows.Count                         
    tempselected = rngSelectionTable(temprow, 2).Value                      
    Crit = rngSelectionTable(temprow, 5).Value                              

    If tempselected = True Then

    For Each r In src.Range("A1:A" & 10)                

         'If r <> 0 _
          And r <> src3.Range("A1") _
          And r <> src3.Range("A2") _
          And r <> src3.Range("A3") _
          Then myFinalResult = r

        For Each comparisonRange In src3.Range("A1:A" & 3) 'does not work
          If r <> 0 And r <> comparisonRange 'does not work
              Next comparisonRange 'does not work
          Then myFinalResult = r 'does not work

        'rest of the code below
             If myFinalResult = Crit Then                                 
                 If CopyRange Is Nothing Then                        
                     Set CopyRange = r.EntireRow                 
                           Else
                     Set CopyRange = Union(CopyRange, r.EntireRow) 
                 End If
             End If   
       Next r
    End If
  Next temprow

1 个答案:

答案 0 :(得分:1)

这样的事情应该有效:

Sub test()
    Dim r As Range, rng10 As Range, rng3 As Range
    Set rng10 = Sheet1.Range("a1:a10")
    Set rng3 = Sheet2.Range("$a$1:$a$3")

    For Each r In rng10
        If Application.WorksheetFunction.CountIf(rng3, r) > 0 Then
            'proceed here
        End If
    Next r
End Sub