使用循环的Excelmacros

所以我有两列17&18,我有多行,如:

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

等等…我想要做的是从第2行第17列开始,抓住ttt,然后看看是否再次出现在第17列或第18列。如果不是,我需要显示一条消息给用户,如果它是不是,说20行第18栏我需要忽略它,并表明我已经find了这个值,并不想再次遇到它时,我下了。

我希望这是有道理的 …

我认为正确的做法是使用一个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 

有没有人试图做到这一点?

我不会使用范围.Find方法。 只需使用Application.Match函数或WorksheetFunction.CountIf函数即可。 为了在第二次/后续的过程中忽略它,你将需要存储在内存中忽略的值的列表,我build议使用这个字典对象。

也许这样(未经testing):

 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