Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

InStr(1, cell.Value, "-") doesn't seem to be working with Not

Tags:

excel

vba

I have a conditional that doesn't seem to work.

If Not InStr(1, cell.Value, "-") Then
    'Do Something
Else
    'Do something else
End If

Where cell.Value are either numbers in a spreadsheet with a dash: "6621-123", or without a dash: "555321"

The first If let's both through and the Else is ignored. Any ideas why this isn't working?

like image 812
Justin L. Avatar asked Jan 07 '16 16:01

Justin L.


People also ask

How do I use the InStr function in Excel?

The syntax of VBA InStr is “InStr([start],string1,string2,[compare]).” In comparison, the syntax of InStrRev is “InStrRev(string1,string2,[start,[compare]]).” If the “start” argument is omitted, the InStr begins to search from the starting (first position) of the string.

What does InStr return if not found?

The INSTR function returns a numeric value. The first position in string is 1. If substring is not found in string, then the INSTR function will return 0.

How does InStr work in VBA?

The InStrB function is used with byte data contained in a string. Instead of returning the character position of the first occurrence of one string within another, InStrB returns the byte position.

How do I find a specific text in Excel VBA?

INSTR Function Using VBA to Find String in a Cell You can find any string and its position from any cell. The VBA InStr Function indicates if a text string is detected in another text string. It returns 0 if the text is not found. Otherwise, it returns the character position where the text is located.


1 Answers

InStr returns 0 on no match (not -1 as VBA string indexes are 1 based) and not 0 is true (-1); so are all other possible values > 0 that can be returned.

If InStr(1, cell.Value, "-") = 0 Then
    '// not present
Else
    '// present  
like image 181
Alex K. Avatar answered Oct 04 '22 03:10

Alex K.