使用Excel VBA在单元格/字符串中查找URL

时间:2017-03-15 12:27:56

标签: excel vba excel-vba excel-formula

我有一个包含各种信息的单元格/字符串,包括RAW http:// links。

我想找到一种方法来提取这些RAW URL并将它们转换为HTML链接(等等不是Excel中的可点击链接)。见下面的例子:

Source: This is a sample link: http://www.bbc.co.uk Please visit.
Output: This is a sample link: <a href="http://www.bbc.co.uk">http://www.bbc.co.uk</a> Please visit.

我已经涉足了替换功能,但这似乎没有给我所需的结果。

任何帮助表示感谢。

3 个答案:

答案 0 :(得分:2)

哦-key-doh-key ...所以你是' ...寻找从哪里开始的指针。'。这是一个开始:

=SUBSTITUTE(REPLACE(A2, FIND(" ", A2, FIND("http", A2)), 1, """>"), " http", "<a href=""http")&"</a>"

现在,您可以使用相同的函数和方法来优化它,以将URL去除到锚元素中。

enter image description here

答案 1 :(得分:1)

如果您的输入位于A1中,请将其放在A2中以获取已清理的链接:

=TRIM(SUBSTITUTE(SUBSTITUTE(A1,"This is a sample link: ","")," Please visit.",""))

在A2中使用已清理的链接:

="This is a sample link: <a href="""&A2&""">"&A2&"</a> Please visit."

或两者合并(在A1中输入):

="This is a sample link: <a href="""&TRIM(SUBSTITUTE(SUBSTITUTE(A1,"This is a sample link: ","")," Please visit.",""))&""">"&TRIM(SUBSTITUTE(SUBSTITUTE(A1,"This is a sample link: ","")," Please visit.",""))&"</a> Please visit."

答案 2 :(得分:0)

这是一个将替换的UDF。并且还应该在同一个字符串中使用多个URL。 IT使用正则表达式引擎来完成工作,并会找到各种协议的URL(例如http,https,ftp,File)

此外,如果链接是句子的一部分,则结尾处的标点符号(例如句号,逗号等)将不会包含在html标记中。

Option Explicit
Function LinkToHTML(S As String) As String
    Dim RE As Object
    Const sPat As String = "\b(https?|ftps?|file)://[-A-Z0-9+&@#/%?=~_|$!:,.;]*[A-Z0-9+&@#/%=~_|$]"
    Const sRepl As String = "<a href=""$&"">$&</a>"

Set RE = CreateObject("vbscript.regexp")
With RE
    .Global = True
    .Pattern = sPat
    .ignorecase = True
    LinkToHTML = .Replace(S, sRepl)
End With

End Function

enter image description here