How to do a search for like *criteria* in vba?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • copleyuk
    New Member
    • May 2010
    • 39

    How to do a search for like *criteria* in vba?

    I'm using the following to builder a search criteria:

    Code:
    Private Sub btnSearch_Click()
        
        ' Update the record source
        Me.frmsubClients.Form.RecordSource = "SELECT * FROM qryClientData " & BuildFilter
        
        ' Requery the subform
        Me.frmsubClients.Requery
    End Sub
    And then using this to set the filter:

    Code:
    Private Function BuildFilter() As Variant
        Dim Varwhere As Variant
    
    If Me.Reference > "" Then
            Varwhere = Varwhere & "[referencenumber] LIKE """ & Me.Reference & "*"" AND "
        End If
    This works great for searches where the wildcard follows the search criteria. However, no matter how I juggle it I cannot get the search to work for a contains criteria. ie

    Code:
    If Me.Reference > "" Then
            Varwhere = Varwhere & "[referencenumber] LIKE "*"" & Me.Reference & "*"" AND "
    Can anyone point out where I am going wrong?

    Thanks :)
  • Delerna
    Recognized Expert Top Contributor
    • Jan 2008
    • 1134

    #2
    have you tried it like this
    I bolded it where it is different to yours
    Code:
    LIKE [B]""*" [/B]& Me.Reference & "*"" AND "
    If that doesn't work then maybe something like this
    Code:
    LIKE [B]""" & "*"[/B] & Me.Reference & "*"" AND "
    or
    Code:
    LIKE [B]" & chr(34) & "*" [/B]& Me.Reference & "*"" AND "
    It's just a matter of getting the correct number of quotations
    and the * in the right place

    You had the first * in the wrong place
    It would have read as this to the Query engine
    Code:
       like * "test string*"
    but you mean
    Code:
       like "*test string*"

    Comment

    • copleyuk
      New Member
      • May 2010
      • 39

      #3
      First one worked a treat!!

      Thanks very much :)

      Comment

      • NeoPa
        Recognized Expert Moderator MVP
        • Oct 2006
        • 32653

        #4
        I suspect you'd find it easier (or harder to make mistakes) using ANSI Standards in String Comparisons.

        Comment

        Working...