Google Answers Logo
View Question
 
Q: Need VBA/Word macro to create a new file with a hyperlink to it. ( Answered 5 out of 5 stars,   0 Comments )
Question  
Subject: Need VBA/Word macro to create a new file with a hyperlink to it.
Category: Computers > Programming
Asked by: solomind-ga
List Price: $200.00
Posted: 09 Jan 2004 12:54 PST
Expires: 08 Feb 2004 12:54 PST
Question ID: 294830
I need a VBA/Word macro that works in MS Word 97 AND MS Word 2000 and
does the following:

1. If there is no text currently highlighted in current document (the
'initial' document) or it was not loaded from a file, then return an
error.
2. Identify the directory this document was loaded from.
3. Find all files in this directory of the form '~XXXX.doc', where
XXXX is a zero-padded 4 digit positive integer. Add one to the largest
such value to get YYYY.
4. Copy the file '~0001.doc' to the file '~YYYY.doc' and make the
currently highlighted text a hyperlink to this document.
5. Modify this new document to add a hyperlink labelled '[up]' to the
top of the document, which links back to the initial document. Save
and close the new document.
Answer  
Subject: Re: Need VBA/Word macro to create a new file with a hyperlink to it.
Answered By: hammer-ga on 16 Jan 2004 15:24 PST
Rated:5 out of 5 stars
 
Below is a Word VBA macro that does what you need. I've tested it on
Word 2000, Word 97 and Word 2002. The code is commented, but please
let me know if you need any clarification on the code.

Notes:
1. No line of code should wrap. You may need to unwrap lines after
pasting into Word.
2. To access the Word VBA code editor, press Alt-F11 from your main
document. Paste this routine into the General code area.

Good luck with your Word project!

- Hammer

---------------------------------

Sub LinkNewDoc()
Dim strDirectory As String
Dim strFilename As String
Dim strThisFilename As String
Dim strName As String
Dim intMax As Integer
Dim intCompare As Integer
Dim intPos As Integer
Dim hypLink As Hyperlink
Dim docNew As Document
Dim pp As Word.Paragraph

    ' Get the current document path
    strThisFilename = ActiveDocument.FullName
    
    ' Make sure there is some text selected
    If ActiveDocument.ActiveWindow.Selection.Start <>
ActiveDocument.ActiveWindow.Selection.End Then
        strDirectory = ActiveDocument.Path
        ' Make sure this file is not unnamed
        If Len(strDirectory) > 0 Then
            intMax = 0
            ' Get the list of files matching pattern
            strFilename = Dir(strDirectory & Application.PathSeparator
& "~????.doc")
            Do While strFilename <> ""
                intPos = InStr(1, strFilename, ".")
                ' Confirm pattern match
                If (intPos = 6) And (Left(strFilename, 1) = "~") Then
                    ' Parse out the number
                    strName = Mid(strFilename, 2, 4)
                    intCompare = CInt(strName)
                    ' Get the highest number
                    If intCompare > intMax Then
                        intMax = intCompare
                    End If
                End If
                strFilename = Dir
            Loop
            intMax = intMax + 1
            
            ' Build the new filename
            strFilename = strDirectory & Application.PathSeparator &
"~" & Format(intMax, "0000") & ".doc"
            ' Make sure the template file exists
            If Dir(strDirectory & Application.PathSeparator &
"~0001.doc") <> "" Then
                ' Copy the template file to the new name
                FileCopy strDirectory & Application.PathSeparator &
"~0001.doc", strFilename
                ' Create the hyperlink in the current document
                Set hypLink =
ActiveDocument.Hyperlinks.Add(ActiveDocument.ActiveWindow.Selection.Range,
strFilename)
                If Not hypLink Is Nothing Then
                    ' Open the new document
                    Set docNew = Documents.Open(strFilename)
                    If Not docNew Is Nothing Then
                        ' Write the link text into the new document
                        ' and link it to the current document
                        Set pp = docNew.Paragraphs.Add
                        pp.Range.Text = "Up"
                        Set hypLink = docNew.Hyperlinks.Add(pp.Range,
strThisFilename)
                        If Not hypLink Is Nothing Then
                            ' Save all open documents
                            Documents.Save True, wdWordDocument
                            ' Close the new document
                            docNew.Close
                        Else
                            MsgBox "Failed to create hyperlink in new document."
                        End If
                    Else
                        MsgBox "Could not open new documnt."
                    End If
                Else
                    MsgBox "Failed to create hyperlink in main document."
                End If
            Else
                MsgBox "Template file does not exist."
            End If
        Else
            MsgBox ("Invalid document path.")
        End If
    Else
        MsgBox "No text selected!"
    End If
 
' Clean up
strDirectory = ""
strFilename = ""
strThisFilename = ""
strName = ""
Set hypLink = Nothing
Set docNew = Nothing
Set pp = Nothing
End Sub

Request for Answer Clarification by solomind-ga on 16 Jan 2004 16:57 PST
Everything working well so far in Word97/2000 except that the 'up'
link appears at the bottom of the copied (new) document rather than
the top ...

Thanks,

Clarification of Answer by hammer-ga on 17 Jan 2004 05:38 PST
Here you go! This version will force the link to the top of the document.

- Hammer

--------------------------------------------------

Sub LinkNewDoc()
Dim strDirectory As String
Dim strFilename As String
Dim strThisFilename As String
Dim strName As String
Dim intMax As Integer
Dim intCompare As Integer
Dim intPos As Integer
Dim hypLink As Hyperlink
Dim docNew As Document
Dim rngDoc As Range

    ' Get the current document path
    strThisFilename = ActiveDocument.FullName
    
    ' Make sure there is some text selected
    If ActiveDocument.ActiveWindow.Selection.Start <>
ActiveDocument.ActiveWindow.Selection.End Then
        strDirectory = ActiveDocument.Path
        ' Make sure this file is not unnamed
        If Len(strDirectory) > 0 Then
            intMax = 0
            ' Get the list of files matching pattern
            strFilename = Dir(strDirectory & Application.PathSeparator
& "~????.doc")
            Do While strFilename <> ""
                intPos = InStr(1, strFilename, ".")
                ' Confirm pattern match
                If (intPos = 6) And (Left(strFilename, 1) = "~") Then
                    ' Parse out the number
                    strName = Mid(strFilename, 2, 4)
                    intCompare = CInt(strName)
                    ' Get the highest number
                    If intCompare > intMax Then
                        intMax = intCompare
                    End If
                End If
                strFilename = Dir
            Loop
            intMax = intMax + 1
            
            ' Build the new filename
            strFilename = strDirectory & Application.PathSeparator &
"~" & Format(intMax, "0000") & ".doc"
            ' Make sure the template file exists
            If Dir(strDirectory & Application.PathSeparator &
"~0001.doc") <> "" Then
                ' Copy the template file to the new name
                FileCopy strDirectory & Application.PathSeparator &
"~0001.doc", strFilename
                ' Create the hyperlink in the current document
                Set hypLink =
ActiveDocument.Hyperlinks.Add(ActiveDocument.ActiveWindow.Selection.Range,
strFilename)
                If Not hypLink Is Nothing Then
                    ' Open the new document
                    Set docNew = Documents.Open(strFilename)
                    If Not docNew Is Nothing Then
                        ' Write the link text into the new document
                        ' and link it to the current document
                        Set rngDoc = docNew.Range(Start:=0, End:=0)
                        rngDoc.InsertBefore "Up" & vbCrLf & vbCrLf
                        Set rngDoc = docNew.Range(Start:=0, End:=2)
                        Set hypLink = docNew.Hyperlinks.Add(rngDoc,
strThisFilename)
                        If Not hypLink Is Nothing Then
                            ' Save all open documents
                            Documents.Save True, wdWordDocument
                            ' Close the new document
                            docNew.Close
                        Else
                            MsgBox "Failed to create hyperlink in new document."
                        End If
                    Else
                        MsgBox "Could not open new documnt."
                    End If
                Else
                    MsgBox "Failed to create hyperlink in main document."
                End If
            Else
                MsgBox "Template file does not exist."
            End If
        Else
            MsgBox "Invalid document path."
        End If
    Else
        MsgBox "No text selected!"
    End If
 
' Clean up
strDirectory = ""
strFilename = ""
strThisFilename = ""
strName = ""
Set hypLink = Nothing
Set docNew = Nothing
Set rngDoc = Nothing
End Sub
solomind-ga rated this answer:5 out of 5 stars
Does exactly as requested.

Comments  
There are no comments at this time.

Important Disclaimer: Answers and comments provided on Google Answers are general information, and are not intended to substitute for informed professional medical, psychiatric, psychological, tax, legal, investment, accounting, or other professional advice. Google does not endorse, and expressly disclaims liability for any product, manufacturer, distributor, service or service provider mentioned or any opinion expressed in answers or comments. Please read carefully the Google Answers Terms of Service.

If you feel that you have found inappropriate content, please let us know by emailing us at answers-support@google.com with the question ID listed above. Thank you.
Search Google Answers for
Google Answers  


Google Home - Answers FAQ - Terms of Service - Privacy Policy