我是VBA的新手,并尝试使用If-Statement制作两个循环 - 根据此代码:
Sub Filter()
For Count = Worksheets("STR").Range("A1").End(xlDown).Row To 1 Step -1
For Counter = 5 To Worksheets("Filter").Range("A5").End(xlDown).Row
With Worksheets("STR").Range("C" & Count)
If .Value Like Worksheets("Filter").Range("C" & Counter).Value _
Or .Value Like Worksheets("Filter").Range("D" & Counter).Value _
Or .Value Like Worksheets("Filter").Range("E" & Counter).Value _
Or .Value Like Worksheets("Filter").Range("A" & Counter).Value Then
Worksheets("STR").Range("D" & Count) = "X"
'Worksheets("STR").Row("A" & Count).EntireRow.Delete
Next Counter
End If
End With
Next Count
End Sub
在某个阶段,我认为它一遍又一遍地循环,直到它崩溃。调试器告诉我它是“End If”行,但我没有看到什么是错的。有没有办法让这更容易?
提前致谢!
答案 0 :(得分:2)
四件事
End(xlDown)
来查找最后一行。有关如何查找最后一行的信息,请参阅此link。ScreenUpdating
设置为False并重新设置。应用上述4条建议后,您的代码将如下所示。
Option Explicit
Sub Filter()
Dim LastRowSTR As Long, LastRowFilter As Long
On Error GoTo Whoa
Application.ScreenUpdating = False
With Sheets("STR")
LastRowSTR = .Range("A" & .Rows.Count).End(xlUp).Row
End With
With Sheets("Filter")
LastRowFilter = .Range("A" & .Rows.Count).End(xlUp).Row
End With
For Count = LastRowSTR To 1 Step -1
For Counter = 5 To LastRowFilter
With Worksheets("STR").Range("C" & Count)
If .Value Like Worksheets("Filter").Range("C" & Counter).Value _
Or .Value Like Worksheets("Filter").Range("D" & Counter).Value _
Or .Value Like Worksheets("Filter").Range("E" & Counter).Value _
Or .Value Like Worksheets("Filter").Range("A" & Counter).Value Then
Worksheets("STR").Range("D" & Count) = "X"
'Worksheets("STR").Row("A" & Count).EntireRow.Delete
End If
End With
Next Counter
Next Count
LetsContinue:
Application.ScreenUpdating = True
Exit Sub
Whoa:
MsgBox Err.Description
Resume LetsContinue
End Sub
有兴趣阅读。
主题:'Err'是人类
LINK :http://siddharthrout.wordpress.com/2011/08/01/to-err-is-human/