+ Reply to Thread
Results 1 to 14 of 14

Find the position of various characters in string

Hybrid View

  1. #1
    Forum Contributor
    Join Date
    06-29-2005
    Posts
    201

    Find the position of various characters in string

    Hi all

    Is it possible to find the location of different characters in a string (using VBA)?
    Normally I would use InStr of InStrRev option in VBA but my situation is a little more complicated.

    The character I am looking for is not always the same, sometimes it is a , or a . or a : or a "blank" etc

    I tried to do it like:
    dim strChar as string
    strChar = "[,.? /]"

    SearchPosition = InStr ("cell location", strChar) (searchposition is the name of the function I am trying to make)
    This works if I define only 1 character, this way it gives me a 0 as outcome

    I have tried to change it to strChar = "[,]" or strChar = "[.]" or strChar = "[ ]" but this doesn't work.

    Can this be done or should I approach it in an other way?

    Thanks in advance
    Hein

  2. #2
    Valued Forum Contributor
    Join Date
    09-21-2011
    Location
    Birmingham UK
    MS-Off Ver
    Excel 2003/7/10
    Posts
    2,188

    Re: Find the position of various characters in string

    You dont need the []'s just instr(1,string, lookfor)
    =instr(1,"N.s",".")
    Hope this helps

    Sometimes its best to start at the beginning and learn VBA & Excel.

    Please dont ask me to do your work for you, I learnt from Reading books, Recording, F1 and Google and like having all of this knowledge in my head for the next time i wish to do it, or wish to tweak it.
    Available for remote consultancy work PM me

  3. #3
    Forum Guru Andy Pope's Avatar
    Join Date
    05-10-2004
    Location
    Essex, UK
    MS-Off Ver
    O365
    Posts
    20,481

    Re: Find the position of various characters in string

    You would need to desconstruct the lookfor variable and loop through the character(s).

    But if you are search for multiple text what value should you return?
    Cheers
    Andy
    www.andypope.info

  4. #4
    Forum Contributor
    Join Date
    06-29-2005
    Posts
    201

    Re: Find the position of various characters in string

    Hi Andy

    What I am looking for is the location of different characters.

    e.g: "work,hobby" should return 5 (look for the location of the comma)
    or: "working.hobby" should return 8 (the location of the dot)
    or: 111,22 should return 4
    or 111.22 should also return 4

    The "dim strChar as string --> strChar = "[,.? /]" " part works if I use it as follows: "if searchPosition like "*" & strChar & "*" etc"

    What I would like to do is to define all possible character that may occur in the string as strChar and use this in the InStr function

    I have tried using replace , to. and / to . but can't get it to work either

    Can you do anything with this

    Hein

  5. #5
    Valued Forum Contributor
    Join Date
    09-19-2008
    Location
    It varies ...
    MS-Off Ver
    Office365 - 64bit
    Posts
    862

    Re: Find the position of various characters in string

    Agree with Andy ... run through the individual characters like this:
        arrChars = Array(".", ",", ":", "-")
        For i = LBound(arrChars) To UBound(arrChars)
            If InStr(1, strYourString, arrChars(i), vbTextCompare) > 0 Then
                'do whatever with it here:
                
                Exit For
            End If
        Next i
    MatrixMan.
    --------------------------------------
    If this - or any - reply helps you, remember to say thanks by clicking on *Add Reputation.
    If your issue is now resolved, remember to mark as solved - click Thread Tools at top right of thread.

  6. #6
    Forum Guru Andy Pope's Avatar
    Join Date
    05-10-2004
    Location
    Essex, UK
    MS-Off Ver
    O365
    Posts
    20,481

    Re: Find the position of various characters in string

    so what should the return value be when

    strChar = ",." and the text is "1. Work,hobby"

    2 or 7 ? EDIT: and should order of search have an effect. That is once something found stop searching

    MatrixMan has provided code for checking multiple items.

  7. #7
    Forum Guru
    Join Date
    08-15-2004
    Location
    Tokyo, Japan
    MS-Off Ver
    2013 O.365
    Posts
    22,834

    Re: Find the position of various characters in string

    Like this?
    Sub test()
        Dim x, e, m As Object
        x = Array("work,hobby", "working.hobby", "111,22", "111.22", "1/2", "#$?!")
        With CreateObject("VBScript.RegExp")
            .Global = True
            .Pattern = "[,\.\?/]"
            For Each e In x
                For Each m In .Execute(e)
                    MsgBox "found """ & m.Value & """ in psotion " & _
                    m.firstindex + 1, , e
                Next
            Next
        End With
    End Sub
    Last edited by jindon; 07-11-2014 at 09:22 AM. Reason: Adjusted for multiple match

  8. #8
    Forum Contributor
    Join Date
    06-29-2005
    Posts
    201

    Re: Find the position of various characters in string

    Hi Andy, MatrixMan

    I think Matrixman´s code might be on to something
    (BTW Andy: your example should return 2)

    The code MatrixMan made needed some additional dim
    I have tried to solve this by changing the code to (BTW: demo is the name of the function):
    "
    dim arrChars as Variant
    arrChars = Array(".", ",", ":", "-")
    dim i as long
    For i = LBound(arrChars) To UBound(arrChars)
    Demo =InStr(1, strYourString, arrChars(i), vbTextCompare)
    Next i
    "

    This works, but only for the last defined characters, all other characters return a 0

    Is there a way take that last obstacle?

    Hein

  9. #9
    Forum Guru
    Join Date
    08-15-2004
    Location
    Tokyo, Japan
    MS-Off Ver
    2013 O.365
    Posts
    22,834

    Re: Find the position of various characters in string

    If you want to edit the search string then
    Sub test()
        Dim myStr As String, x, e, m As Object
        myStr = ",.?/"  '<-  alter this
        x = Array("work,hobby", "working.hobby", "111,22", "111.22", "1/2", "#$?!")
        With CreateObject("VBScript.RegExp")
            .Global = True
            .Pattern = "([\$\(\)\-\^\|\\\[\]\*\+\?\.])"
            myStr = .Replace(myStr, "\$1")
            .Pattern = "[" & myStr & "]"
            For Each e In x
                For Each m In .Execute(e)
                    MsgBox "found """ & m.Value & """ in psotion " & _
                    m.firstindex + 1, , e
                Next
            Next
        End With
    End Sub

  10. #10
    Forum Contributor
    Join Date
    06-29-2005
    Posts
    201

    Re: Find the position of various characters in string

    Hi Jindon

    I think that your solution always assumes that the same text is used: ( x = Array("work,hobby", "working.hobby", "111,22", "111.22", "1/2", "#$?!")

    In reality this varies. The string I am "investigating" are always numbers with a string format; actually they are times. eg. 1.11.11 of 11.11.1 or any combination of digits you can think of.

    I think that MatrixMan's code may be the solution, although some adjusting is required.

    Hein

    PS
    Of course thanks you for your help, much appriciated

  11. #11
    Forum Guru
    Join Date
    08-15-2004
    Location
    Tokyo, Japan
    MS-Off Ver
    2013 O.365
    Posts
    22,834

    Re: Find the position of various characters in string

    You can loop through the cell or what ever you like to do.

    It was just a sample to show how it works.

    If you don't know how to do it.... just ask.

  12. #12
    Forum Guru Andy Pope's Avatar
    Join Date
    05-10-2004
    Location
    Essex, UK
    MS-Off Ver
    O365
    Posts
    20,481

    Re: Find the position of various characters in string

    Function SearchPosition(Text As String, SubTexts As String) As Long
    
        Dim FirstPos As Long
        Dim Pos As Long
        Dim Index As Long
        
        For Index = 1 To Len(SubTexts)
            Pos = InStr(1, Text, Mid(SubTexts, Index, 1), vbTextCompare)
            If Pos > 0 Then
                If FirstPos = 0 Then
                    FirstPos = Pos
                Else
                    If Pos < FirstPos Then
                        FirstPos = Pos
                    End If
                End If
            End If
        Next
        
        SearchPosition = FirstPos
        
    End Function
    
    Sub Test()
    
        Dim Text As String
        Dim SubTexts As String
        
        SubTexts = "[.,/?]"
        
        Text = "1. Work, hobbys"
        MsgBox SearchPosition(Text, SubTexts)
        
        Text = "working.hobby"
        MsgBox SearchPosition(Text, SubTexts)
        
        Text = "111,22"
        MsgBox SearchPosition(Text, SubTexts)
        
        Text = "111.22"
        MsgBox SearchPosition(Text, SubTexts)
        
    End Sub

  13. #13
    Forum Contributor
    Join Date
    06-29-2005
    Posts
    201

    Re: Find the position of various characters in string

    Hi Andy

    Thanks big time!
    Your solution gives exactly the outcome I was looking for.
    Never thought that an (in my mind) simple question involved so much code.

    Anyway: I can go further now.
    Once again: Thank you

    Hein

  14. #14
    Valued Forum Contributor
    Join Date
    09-19-2008
    Location
    It varies ...
    MS-Off Ver
    Office365 - 64bit
    Posts
    862

    Re: Find the position of various characters in string

    Apologies - stepped away for a bit; glad Andy was able to help ... here's another option that runs through a range (which you can pass into this as a parameter if you like) and let's you do whatever you're doing with the string from the first position where any of the characters are found:
    Sub FindFirstChar()
    Dim arrChars As Variant
    Dim i As Long
    Dim intPos As Integer, intFirstPos As Integer
    Dim rng As Range, cel As Range
    
        Set rng = Me.Range("A1:A10")
        arrChars = Array(".", ",", ":", "-", "=")
        
        For Each cel In rng
            intFirstPos = Len(cel.Text) + 1
            For i = LBound(arrChars) To UBound(arrChars)
                intPos = InStr(1, cel.Text, arrChars(i), vbTextCompare)
                If intPos > 0 Then
                    If intPos < intFirstPos Then intFirstPos = intPos
                End If
            Next i
            If intFirstPos < Len(cel.Text) + 1 Then
                'a character was found - first one is at intFirstPos; do whatever you want to do with it here:
                
            Else
                'none of the characters were found - do something else here:
                
            End If
        Next cel
        
    End Sub

+ Reply to Thread

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Similar Threads

  1. find position of special characters in string
    By RonanKeating in forum Excel Programming / VBA / Macros
    Replies: 7
    Last Post: 11-08-2012, 02:41 PM
  2. Add the word ERROR in the 133rd position after a string of characters in a cell
    By viantahu in forum Excel Programming / VBA / Macros
    Replies: 1
    Last Post: 05-24-2012, 04:32 PM
  3. How do I find a specific characters position in a string variable
    By paul@excelmastery.com in forum Excel Programming / VBA / Macros
    Replies: 3
    Last Post: 03-11-2006, 10:30 AM
  4. [SOLVED] find nth position of a string
    By TUNGANA KURMA RAJU in forum Excel General
    Replies: 6
    Last Post: 10-18-2005, 09:05 AM
  5. [SOLVED] find position of a number in a string
    By fullers80 in forum Excel Formulas & Functions
    Replies: 1
    Last Post: 09-07-2005, 12:05 AM

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts

Search Engine Friendly URLs by vBSEO 3.6.0 RC 1