Excel VBA 简单的 if not 语句
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/42115086/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Excel VBA simple if not statement
提问by Josh
I am trying to run a relatively simple loop to pull out values I don't want from a list.
我正在尝试运行一个相对简单的循环来从列表中提取我不想要的值。
Everything below is working correctly other than my "Not" statement which does not create an error...
除了我的“Not”语句不会产生错误之外,下面的所有内容都正常工作......
it just doesn't seem to do anything at all.
它似乎根本没有做任何事情。
Set myRange = Range("A49:A150")
For Each myCell In myRange
If myCell Like "*msn.com*" Or _
myCell Like "*messaging.microsoft.com*" Or _
Not myCell Like "*.com*" Then
myCell.Delete
End If
Next myCell
I am fairly certain I have a simple mistake in here somewhere but I have been unable to find it.
我相当确定我在这里的某个地方有一个简单的错误,但我一直无法找到它。
回答by cyboashu
Its not the Notstatement. Your issue is that when you delete the cell, you range changes and so your loop is missing data. If Cell A49 is deleted then the value at A50 moves up to A49 and is never checked. Aggregate your cells which qualify to get deleted and then delete them in one go.
它不是Not声明。您的问题是,当您删除单元格时,范围会发生变化,因此您的循环缺少数据。如果单元格 A49 被删除,则 A50 处的值向上移动到 A49,并且永远不会被检查。聚合您有资格被删除的单元格,然后一次性删除它们。
Sub test()
Dim rngDelete As Range
Set myrange = Range("A1:A3")
For Each mycell In myrange.Cells
If mycell Like "*msn.com*" Or _
mycell Like "*messaging.microsoft.com*" Or _
Not mycell Like "*.com*" Then
If Not rngDelete Is Nothing Then
Set rngDelete = Union(rngDelete, mycell)
Else
Set rngDelete = mycell
End If
End If
Next mycell
If Not rngDelete Is Nothing Then
rngDelete.Delete
End If
End Sub

