Excel宏使用循环

时间:2014-06-30 17:32:12

标签: excel vba loops excel-vba

所以我有两列17和18,其中有多行,例如:

17  |  18<br>
ttt | xxx<br>
tty | xxy<br>
eer | eet<br>
fff | fft<br>

...等 我想要做的是从第2行第17列开始,抓住ttt,然后查看是否在第17或18列中再次出现。如果不是,我需要向用户显示消息,如果是,请说Row 20第18栏我需要忽略它并标记我已经找到了这个值,并且当我到达那里时不想再遇到它。

我希望这是有道理的......

我认为正确的做法是使用Do循环并查看类似的内容:

    Dim X As Range
    Do While Cells(X, 17) <> ""
        Do While Cells(X,18) <> ""
            Cells.Find(What:=X.Value, After:=activeCell).Active
        Loop
    Loop

以前有人试过这样做吗?

1 个答案:

答案 0 :(得分:1)

我不会使用范围.Find方法。仅使用Application.Match函数或WorksheetFunction.CountIf函数。为了在第二次/后续传递中忽略它,你需要在内存中存储要忽略的值列表,我建议使用字典对象。

这样的事可能(未经测试):

Sub foo()
Dim column1 as Range
Dim rngToCheck as Range
Dim r as Range
Dim dict as Object


'use a dictionary object to keep track of the items that appear more than once
Set dict = CreateObject("Scripting.Dictionary")

Set column1 = Range("A1:A100") 'Modify as needed -- only the first column

Set rngToCheck = Range("A1:B100") 'Modify as needed -- both columns

'Check each value in column1 against the entire range
For each r in column1
    'ignoring anything that already has been added to the dictionary
    If not dict.Exists(r.Value) Then
        If WorksheetFunction.CountIf(rngToCheck, r.Value) > 1 then 
            'if it appears more than once then add it to the dictionary so to ignore
            ' it the next time the macro encounters this value:
            dict(r.Value) = dict(r.Value)
        Else
            'if this value only appears once, then it doesn't appear anywhere else, _
            ' so msgbox to the user. Modify msgbox as needed:
            MsgBox r 

        End If
    End If
Next

End Sub