如何使用Application.Intersect方法

时间:2018-01-08 16:25:48

标签: excel vba excel-vba

大家晚上好,

正如标题所示,我在excel vba中的Application.Intersect方法有问题。

这是我的情况:

I have 3 columns (A1:A7 , B1:B7 , C1:C7). My aim is take the values contained in A18:B18 , D18:E18 , G18:I18 one by one, and check if each of them is contained in each of the 3 columns described above

示例:A1是A18中的A18?是B18在A1:A7? .... I18是否在A1:A7中受到关注?写下结果,然后转到下一列。

为此,我编写了以下代码:

Sub Macro1() 
Dim column As Range
Dim val As Range
Dim table As Range
Set table = Range("A1:C7")
Dim result As Range
Set result = Range("A9:C9")
Dim b As Integer
b = 0
Dim i As Integer
i = 1
Dim control1 As Range
Set control1 = Range("A18")
Dim control2 As Range
Set control2 = Range("B18")
Dim control3 As Range
Set control3 = Range("D18")
Dim control4 As Range
Set control4 = Range("E18")
Dim control5 As Range
Set control5 = Range("G18")
Dim control6 As Range
Set control6 = Range("H18")
Dim control7 As Range
Set control7 = Range("I18")
For Each column In table.Columns
    Set isect1 = Application.Intersect(control1, table.Columns(i).val)
        If (Not (isect1 Is Nothing)) Then
            b = b + 1
        End If
    Set isect2 = Application.Intersect(control2, table.Columns(i).val)
        If (Not (isect2 Is Nothing)) Then
            b = b + 1
        End If
    Set isect3 = Application.Intersect(control3, table.Columns(i).val)
        If (Not (isect3 Is Nothing)) Then
            b = b + 1
        End If
    Set isect4 = Application.Intersect(control4, table.Columns(i).val)
        If (Not (isect4 Is Nothing)) Then
            b = b + 1
        End If
    Set isect5 = Application.Intersect(control5, table.Columns(i).val)
        If (Not (isect5 Is Nothing)) Then
            b = b + 1
        End If
    Set isect6 = Application.Intersect(control6, table.Columns(i).val)
        If (Not (isect6 Is Nothing)) Then
            b = b + 1
        End If
    Set isect7 = Application.Intersect(control7, table.Columns(i).val)
        If (Not (isect7 Is Nothing)) Then
            b = b + 1
        End If
    Set isect8 = Application.Intersect(control8, table.Columns(i).val)
        If (Not (isect8 Is Nothing)) Then
            b = b + 1
        End If
        i = i + 1
        If b = 8 Then
            result(i).val= "ok"
        Else
            result(i).val= "no"
        End If
Next column
End Sub

问题是:

  • Application.Intersect方法返回始终相同的结果

  • 可能是一种更简单的方法,但我找不到它

  • 每次我设置isect都会给我一个错误:"必要的对象"

谢谢大家的帮助!

编辑:我尝试使用Set isect1 = Application.Intersect(control1, table.Columns(i).val)更改Set isect1 = Application.Intersect(control1, table.Columns(i)),但始终没有相交

EDIT2:感谢TimWilliams的帮助!

1 个答案:

答案 0 :(得分:1)

您应该使用COUNTIF方法:

Dim sht, col, c, v

Set sht = ActiveSheet
For Each col In sht.Range("A1:C7").Columns
For Each c In sht.Range("A18:H18").Cells
    v = Application.CountIf(col, c)
    Debug.Print c.Value & IIf(v > 0, " is ", " is not ") & _
           "contained in " & col.Address()
Next c
Next col