简体   繁体   中英

Excel VBA Code to search range of cells to see if it contains a space

I have search high and low, but I am after a vba code to search a range, ie A1:A1000, and if it finds a cell that contains a space, then to pop up with a message box.

Thanks

How about..

Set r = Range("A1:A1000").Find(What:=" ", LookIn:=xlFormulas, LookAt _
        :=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:= _
        False, SearchFormat:=False)
If r Is Nothing Then
' code to run if nothing found
Else
 MsgBox "Space found in cell " & r.Address
End If

EDIT - removed the After: parameter as this caused issues when cell beyond search area was active.

Just an example:

Dim cell As Range

Set cell = Range("A1:A1000").Find(What:=" ", After:=ActiveCell, LookIn:=xlFormulas, _
        LookAt:=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
        MatchCase:=False, SearchFormat:=False)

If cell Is Nothing Then
    Stop 'do something
Else
    Stop 'do something else
End If

More info: https://msdn.microsoft.com/en-us/library/office/ff839746.aspx

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM