• home
  • forum
  • my
  • kt
  • download
  • VBA: Find Text in a String (instr)

    Author: 2009-07-20 08:39:22 From:

    You can use the instr function in VBA to test if a string contains certain text. The result is the number of times the specified text appears in the string.

    The following code snippet tests the string “Look in this string” for the word “Look”. The result is 1 since the word appears once.

    Public Sub FindSomeText()
    
    MsgBox InStr("Look in this string", "Look")
    
    End Sub

    Sidenote: This test is case senstive. To skip the case sensitive check, enclose the look-in string and test string in Ucase(). Example

    This returns 0 becuase the case is wrong for the word “look”

    MsgBox InStr("Look in this string", "look")
    

    However the following returns 1 becuase it turns both strings to all caps before evaluating:

    MsgBox InStr(UCase("Look in this string"), UCase("look"))
    

    A quick use of the instr in an if…then statement
    Public Sub FindSomeText()
    
    If InStr("Look in this string", "look") = 0 Then
    MsgBox "woops, no match"
    Else
    MsgBox "at least one match"
    End If
    
    End Sub

    discuss this topic to forum

    relation tutorial

    No information

    Category

      Basics (41)
      Charts and Graphs (12)
      Formatting (27)
      Functions (14)
      Macros (10)

    New

    Hot