如何在word文档中查找超链接?

时间:2017-01-21 14:55:50

标签: vb.net hyperlink ms-word

我正在研究VB 2015,但我遇到了问题。 我想在word文档中找到包含带有多个包含超链接的单词的段落的超链接。如何查找所有超链接并将其列在文本文件或文本框中?

Public Class Form1

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim wa As Microsoft.Office.Interop.Word.Application
        Dim wd As Microsoft.Office.Interop.Word.Document
        Dim wp As Microsoft.Office.Interop.Word.Paragraph
        wa = CreateObject("Word.Application")
        wa.Visible = False
        wd = wa.Documents.Add
        wp = wd.Content.Paragraphs.Add
        wp.Range.Paste()
        wd.SaveAs("F:\sample.docx")

        Dim colHyperlinks As String = wd.Hyperlinks.ToString

        For Each objHyperlink In colHyperlinks
            TextBox1.Text = objHyperlink.TextToDisplay
        Next

        wa.Quit()
    End Sub

End Class

1 个答案:

答案 0 :(得分:0)

正如上面评论中所述,您在string 集合 对象上声明了Word.Hyperlinks类型。因此,您只能获得一个字符串,而不是任何其他字符串。请参阅下面的代码,评论它的作用......

注意:代码已经过试用和测试

'returns a collection of links, not a string
Dim colHyperlinks As Word.Hyperlinks = wd.Hyperlinks() 

以下代码只是一个LINQ语句,用于将所有超链接转换为List(Of String)。您可以根据需要进行循环,然后根据需要将其添加到Textbox ...

'get all the hyperlinks
Dim arr As List(Of String) = (From hl As Word.Hyperlink In colHyperlinks Select hl.TextToDisplay).ToList()

'show the url's
TextBox1.Text = String.Join(Environment.NewLine, arr)

或者如果你愿意,只需一行......

TextBox1.Text = String.Join(Environment.NewLine, (From hl As Word.Hyperlink In colHyperlinks Select hl.TextToDisplay).ToList())