Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

If statement based on a find (search) in Excel...

Status
Not open for further replies.

brans

Programmer
Apr 11, 2001
17
US
Can you do an If statement in Excel based on a Search finding certain criteria?

I want it to do one thing if A1 contains Branch and another thing if A1 contains Region...

Range("A1").Select
Cells.Find(What:="branch", After:=Activecell, LookIn:=xlValues, LookAt:=xlPart, SearchOrder:=xlByColumns, SearchDirection:=xlNext, MatchCase:=False).Activate
Cells.FindNext(After:=Activecell).Activate
ActiveCell.Offset(0, 50).Select
...

I want to be able to find branch and it run the correct code, and I want it to find region and it run different code (or the same code in a different order).

Is there any way to do this?
 
Is this what you are looking for?
Code:
Sub test()
    Dim sVal As String
    sVal = UCase(Range("A1").Text)
    If InStr(1, "BRANCH", sVal) > 0 Then
        'Do your Branch stuff
        MsgBox "Contains Branch"
    ElseIf InStr(1, "REGION", sVal) > 0 Then
        'Do your Region stuff
        MsgBox "Contains Region"
    End If
End Sub
 
Oops! That won't work. I have the strings reversed in the InStr function. Next time I should take the 5 seconds it takes to test it :)
Code:
Sub test()
    Dim sVal As String
    sVal = UCase(Range("A1").Text)
    If InStr(1, sVal, "BRANCH") > 0 Then
        'Do your Branch stuff
        MsgBox "Contains Branch"
    ElseIf InStr(1, sVal, "REGION") > 0 Then
        'Do your Region stuff
        MsgBox "Contains Region"
    End If
End Sub
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top