-1

In Excel VBA, I have the following data in a string:

<a title="" href="/player-profiles/ashley-barnes/" data-hasqtip="19" oldtitle="Ashley Barnes">Barnes (Ashley)</a>

I want to strip the a tags from the string so that I just end up with "Barnes (Ashley)"

I'm assuming the best way to do it would be to remove all characters between < and > symbols, including the symbols. How would I do that?

1
  • Are you pulling this through IE Automation ?
    – Mikku
    Aug 19, 2019 at 15:01

4 Answers 4

5

I would suggest parsing this string as HTML and access what you need based on the actual DOM element:

Public Sub parsehtml()

    Set html = CreateObject("HTMLFile")

    html.body.innerHTML = "<a title="""" href=""/player-profiles/ashley-barnes/"" data-hasqtip=""19"" oldtitle=""Ashley Barnes"">Barnes (Ashley)</a>"

    MsgBox html.getElementsByTagName("a")(0).innerText 'Barnes (Ashley)

End Sub
0
0

You have to determine the string characters that isolate your target. Use either InStr or InStrRev, then pull out the substring between them:

Sub ShowMe()
    Dim html As String
    html = "<a title="""" href=""/player-profiles/ashley-barnes/"" data-hasqtip=""19"" oldtitle=""Ashley Barnes"">Barnes (Ashley)</a>"

    Dim pos1 As Long
    Dim pos2 As Long
    Dim nameOnly As String
    pos1 = InStrRev(html, "</a>")
    pos2 = InStrRev(html, ">", pos1) + 1
    nameOnly = Mid$(html, pos2, pos1 - pos2)
    Debug.Print nameOnly
End Sub
0

Consider the following User Defined Function:

Public Function KillJunk(S As String) As String
    Dim L As Long, s2 As String, CH As String
    Dim Ignore As Boolean, i As Long

    Ignore = False
    L = Len(S)

    For i = 1 To L
        CH = Mid(S, i, 1)
        If CH = "<" Then
            Ignore = True
        End If
        If Ignore Then
            If CH = ">" Then
                Ignore = False
            End If
        Else
            s2 = s2 & CH
        End If
    Next i
    KillJunk = s2
End Function

enter image description here

0

You can use a regular expression to accomplish this as well

You will need to have added a VBA reference to "Microsoft VBScript Regular Expressions x.x"

Sub StripTags()
    Dim htm As String: htm = "<a title="""" href=""/player-profiles/ashley-barnes/"" data-hasqtip=""19"" oldtitle=""Ashley Barnes"">Barnes (Ashley)</a>"
    Dim Regex As New RegExp: Regex.Global = True: Regex.Pattern = "<.*?>"
    Debug.Print Regex.Replace(htm, "")
End Sub

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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