简体   繁体   中英

Excel 2016 Macro to edit Hyperlink

Currently I need to change over hundreds of cells of hyperlinks to a new format that is being used.

Previously we would have for example " https://oldServer:oldPort/project_code/Some_File " and we are now moving to " https://newServer:newPort/project_code/Some_File ".

I only want to be able to change the "oldServer:oldPort" to "newServer:newPort" without changing the rest of the hyperlink.

I know an excel macro would be the easiest solution but I do not have the experience to be able to create one.

You'd want to loop through each of the hyperlink objects in each sheet.

Code something like this should work. (Make sure you backup before testing this, since I can't test on your actual data!)

Also, note that this changes the link but not the text displayed, since I'm not sure what that consists of. The text could be changed with the same procedure by updating TextToDisplay , or else by using Find & Replace.

Edit: (added confirmation on each change.)

Sub changeLinks()

    Const oldPrefix = "https://oldServer:oldPort/"
    Const newPrefix = "https://newServer:newPort/"
    Dim h As Hyperlink, oldLink As String, newLink As String

    For Each h In ActiveSheet.Hyperlinks
        'this will change Address but not TextToDisplay
        oldLink = h.Address
        Debug.Print "Found link: " & oldLink
        If Left(oldLink, Len(oldPrefix)) = oldPrefix Then
                newLink = newPrefix & Right(h.Address, Len(h.Address) - Len(oldPrefix))

                If MsgBox("Click OK to change:" & vbLf & vbLf & oldLink & _
                    vbLf & vbLf & "to" & vbLf & vbLf & newLink, vbOKCancel, _
                    "Confirmation?") <> vbOK Then Exit Sub

                h.Address = newLink
                Debug.Print "  Changed to " & h.Address
        End If
    Next h

End Sub

I removed the hyperlink from the column containing the old server information. Then I created a couple of new columns. I typed in the full path to the new server in the first new columns and filled it down. In the other new column I created a formula to concatenate the full path and the friendly name (which happened to be what the link was originally named). This created the new server path along with the file name. I copied/pasted values of this column and deleted the contents of the first new column I created. I then used the HYPERLINK formula to put the hyperlink and the friendly name back together. It sounds more convoluted than it was - took me longer to write it down here than to actually do it in my Excel spreadsheet. I hope this makes sense.

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