5

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?

2 Answers 2

9

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  
1
  • Praise the lord. Thanks Alex.
    – Justin L.
    Jan 7, 2016 at 17:01
0

The first If let's both through and the Else is ignored.

I would think that if one of the samples' actual Range.Value property contained a hyphen (aka Chr(45) and the other did not then the behavior would not be the same for both of your samples regardless of whether you got the InStr function's syntax correct. What you have is enough to determine a True/False condition¹ although I typically use a CBool wrapper around the Instr to remind myself that its result is being used in a boolean fashion.

I believe that your 'value' showing a hyphen is actually 6621123 not 6621-123 and that number formatting has been applied to the cell (e.g. custom number format of 0000-000. In this case, if you want to determine the existence of a hyphen in the displayed value use the Range.Text property.

If CBool(InStr(1, cell.Text, "-")) Then
    'hyphen exists as seen on worksheet either in .Value or .Text
Else
    'hyphen does not exist as seen on worksheet
End If

¹ In VBA False is zero and for all intents and purposes, True is anything that is not False. Strictly speaking, a True in VBA resolves mathematically as (-1) while a worksheet TRUE resolves as 1.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.