简体   繁体   中英

VBA remove HTML tags from string only removes first character

I want to remove everything from '<' to '>' but the following code only removes the first '<' in the string and keeps the rest of the HTML tags.

This is the code:

Sub SendHTTP()
    Dim myRequest As Object
    Set myRequest = CreateObject("WinHttp.WinHttpRequest.5.1")

    myRequest.Open "Get", _
    "http://tyda.se/search/test?lang[0]=en&lang[1]=sv"

    'Send
    myRequest.Send

    Dim Response, message As String
    Response = myRequest.ResponseText

    'Remove HTML tags
    message = Replace(Response, "<*>", " ", xlPart)


    'Display message
    MsgBox message

End Sub

I also tried using the accepted answer from this question but it still only removes the first '<'

Remove text between specific tags in Microsoft Excel

The VBA Replace function cannot handle wildcards, but the Range.Replace method can. If you write the Response variable to a cell, run the Range.Replace method, and then read the cell value back into the message variable, it will accomplish what you are trying to do.

Sample code:

Sub SendHTTP()
    Dim myRequest As Object
    Set myRequest = CreateObject("WinHttp.WinHttpRequest.5.1")

    myRequest.Open "Get", _
    "http://tyda.se/search/test?lang[0]=en&lang[1]=sv"

    'Send
    myRequest.Send

    Dim Response, message As String
    Response = myRequest.ResponseText

    'Write Response to cell
    With ThisWorkbook.Sheets(1).Range("A1") 'Change this to a cell that is available for your code to use.
        .Value2 = Response
        'Strip HTML tags
        .Replace What:="<*>", Replacement:=" ", LookAt:=xlPart
        'Read value back into variable
        message = .Value2
        'Clear cell
        .ClearContents
    End With


    'Display message
    MsgBox message

End Sub

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM