VBA从字符串中删除HTML标记只删除第一个字符

时间:2016-02-26 22:12:25

标签: html excel vba

我想删除从'<''>'的所有内容,但以下代码仅删除字符串中的第一个'<'并保留其余的HTML标记。

这是代码:

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

我也尝试使用此问题的接受答案,但它仍然只删除了第一个'<'

Remove text between specific tags in Microsoft Excel

1 个答案:

答案 0 :(得分:1)

VBA替换功能无法处理通配符,但Range.Replace方法可以。如果将Response变量写入单元格,请运行Range.Replace方法,然后将单元格值读回消息变量,它将完成您要执行的操作。

示例代码:

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