我以为我已经在这里的答案的帮助下解决了这个问题,但我仍然只删除需要删除的每一行。循环是:
For Each row In ActiveSheet.UsedRange.Rows
'test for v in cell f and delete if there isn't one
str = Cells(row.row, "F").Value
Debug.Print "str is " & str
If InStr(1, str, "V") <> 0 Then
Debug.Print "hello str is " & str
Else
row.Delete Shift:=xlUp
End If
Next row
但是当我在以下行上运行它时:
M 1301
M 1302
M 1401
ES 1501
M 1501
M 1502
MV 1502
M 1503
MV 1503
我最终得到了:
M1301 PMH
M1401 Rod Washer
M1502 Rod Washer
MV1502 Rod Washer
MV1503 Rod Washer
我觉得我疯了。我在循环中也有一个递增计数器,并且认为这是问题但我仍然拥有它,即使我已经停止使用计数器来引用行。
任何指出我认为明显的帮助都会非常感激。
谢谢
答案 0 :(得分:3)
因为您删除了行row.Delete Shift:=xlUp
,例如第4行,所以当您删除该行时,第5行现在变为第4行,然后转到下一行(第5行,即旧行6)。
您可以在删除后添加Row = Row - 1
,也可以采用不同的方式进行反向。
实施例
For X = range("A" & rows.count).end(xlup).row to 2 step - 1
'Do something per row
'Delete a row if need be
Next
这应该给你足够的想法来解决这个问题。
答案 1 :(得分:2)
尝试下面的代码,我尝试使用原始逻辑(尽管有更简单,更简单的方法)。
代码中的注释为注释,
注意:一般情况下,在您的案例中删除Rows
或Option Explicit
Sub DeleteV()
Dim Rng As Range, i As Long, LastRow As Long
Dim Str As String
' I would rather use Worksheets("SheetName") instead
Set Rng = ActiveSheet.UsedRange
LastRow = Rng.Rows.Count + Rng.Row - 1 ' just in case your range starts from the 2nd row (or 3rd...)
' allways loop backwards when deleting rows
For i = LastRow To Rng.Row Step -1
'test for v in cell f and delete if there isn't one
Str = Cells(i, "F").Value
Debug.Print "str is " & Str
If InStr(1, Str, "V") <> 0 Then
Debug.Print "hello str is " & Str
Else
Rows(i).Delete
End If
Next i
End Sub
时,总是会向后循环。
<强> 代码 强>
Key
答案 2 :(得分:1)
我可以建议代码中的一些更改,这将有所帮助:
'always store reference to the sheet in a variable!
Dim sh As Worksheet
Set sh = ActiveSheet
'determine last row in F column
lastRow = sh.Cells(sh.Rows.Count, 6).End(xlUp).Row
For i = lastRow To 1 Step -1
'test for v in cell f and delete if there isn't one
'we make it uppercase, to avoid situation that we didn't match v with V
str = UCase(sh.Cells(i, 6).Value)
Debug.Print "str is " & str
If InStr(1, str, "V") > 0 Then
Debug.Print "hello str is " & str
Else
Rows(i).Delete
End If
Next i
答案 3 :(得分:1)
当您擦除一行时,所有后续行索引都会减一。
这意味着,如果您删除行n
,因为它包含&#34; V&#34;,行n+1
现在是行n
并且不会被测试。
因此,您的代码会跳过每隔一行。
要修复它,请尝试向后浏览行。