简体   繁体   中英

How to find hyperlinks in a word document?

I'm working on a VB 2015 and I have a problem. I want to find hyperlinks in a word document containing a paragraph with several words containing hyperlinks. How can I find all the hyperlinks and list them in a text file or textbox?

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

As mentioned in the comment's above, you are declaring a string type on a Word.Hyperlinks collections object. Therefore you would only ever get one string and not any others. Please see code below, comment's on what it does...

Note: Code tried and tested

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

This code below is just a LINQ statement to get all hyperlinks into a List(Of String) . You can loop through if you want and then add them to the Textbox if you wish...

'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)

Or in just one line if you wish...

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

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