2017-05-26 86 views
0

我花了數小時試圖找出解決此問題的最佳方法,但我沒有解決方案。我試過循環,使用InStr,條件格式w /通配符,但結果從來沒有我想要的。利用InStr比較兩列

我有兩列值,一個是我想要搜索的值,另一個是長字符串,我的值可能坐在任何地方,因此我需要通配符。我想要做的是採取長字符串列的第一行,並將其與較短值的列中的每個值進行比較。如果沒有短值的長字符串被發現,與長串刪除該行並移動到下一個...

我想我已經將其設置是這樣的:

For i = 1 to lastrow, 
    If InStr(longvalue, shortvalue) Then 
    ' Break loop to next i? 
    Else 
     If i = lastrow 
      longvalue.EntireRow.Delete 
     End If 
    End If 
Next i 

任何幫助,將不勝感激......一直拉着我的頭髮在這一個。再看看,我想我需要2個循環,第一個循環遍歷所有的短數值和單個較長的值,然後在它們全部循環後,轉到下一個更長的值。

編輯:本端:

i = 6 
j = 2 
Set sht = ThisWorkbook.Worksheets("SM Summaries") 
lastrow = sht.Cells(sht.Rows.Count, "C").End(xlUp).Row 
reallastrow = lastrow + 1 
For i = 6 To reallastrow 
    For j = 2 To 82 
     If InStr(ActiveWorkbook.Sheets("SM Summaries").Range("C" & i).Value, ActiveWorkbook.Sheets("SM Reference Sheet").Range("H" & j).Value) Then 
      Exit For 
     Else 
      If j = 82 Then 
       ActiveWorkbook.Sheets("SM Summaries").Range("C" & i).EntireRow.ClearContents 
      End If 
     End If 
    Next j 
Next i 

回答

0

當在一個循環中刪除行,你需要循環向後所以循環可以跟蹤正確的行。所以,

For i=lastrow to 1 step -1 
    If InStr(longvalue, shortvalue) Then 
     GoTo Nexti 
    end if 
    if i=1 then 
     longvalue.entirerow.delete 'this assumes longvalue is a cell reference 
    end if 
Nexti: 
Next i 

但我想我會用Find

With Worksheets(1).Range("b1:b500") 
for i=lastrow to 1 step -1 
    Set c = .Find(cells(i,1), lookin:=xlValues, lookat:=xlPart) 'xlPart returns true if just part of the string matches 
    If c Is Nothing Then 'didn't find your string 
     cells(i,2).entirerow.delete 
    end if 
next i 
End With 
+0

感謝馬特!我只是想出了它。與第一部分代碼幾乎相同的答案。我正在通過循環向前邁進,並使用clearcontents而不是deleterow,因爲在我的代碼結束時,我刪除了所有的空白和重複,並且它們全部向上移動。無論什麼作品! – dwirony

+0

好的。好。由於代碼更加簡潔,也可以使用'Find'進行試驗。儘管如此,恭喜你搞清楚了。 –

+0

因此'Find'會自動使用通配符,所以即使我的值是一個更大字符串中的子字符串,它會通過? – dwirony