简体   繁体   中英

Excel Macro VBA to create a hyperlink to another sheet based on the active cell content

I am trying create a hyperlink that links to a cell in another sheet in the same workbook which bases on the text of the cell. I've tried to do it manually and here is the result :

    =HYPERLINK("[Five Ecom - Floor Plan.xlsx]Inventory!" & 
     ADDRESS(MATCH('8th'!F9,Inventory!$A$1:$A$2000,0),1),'8th'!F9)
  • '8th'!F9 - is the current cell
  • Inventory!$A$1:$A$2000 - range of the cell destinations

The friendly text would be the content of the same current cell.

I'm particularly having difficulties on string manipulation here so I decided to separate the code into several variables, to which up to now I am unable to produce the desired output and results into Run-time error '1004'.

Public Sub Convert_To_Hyperlinks()
    Dim cell As Range
    Dim x As String
    Dim y As String
    Dim z As String
    Dim c As String

    For Each cell In Intersect(Selection, ActiveSheet.UsedRange)
        If cell <> "" Then
            c = ActiveCell.Value
            x = "=HYPERLINK(""[Five Ecom - Floor Plan.xlsm]Inventory!"" & ADDRESS(MATCH("""
            y = """, Inventory!$A$1:$A$2000,0),1),"""
            z = """)"
            ActiveCell.FormulaR1C1 = x & c & y & c & z
        End If
    Next
End Sub

Your macro will work if you replace:

ActiveCell.FormulaR1C1 = x & c & y & c & z

with:

ActiveCell.Formula = x & c & y & c & z

This assumes that the Match() finds what it is looking for.

For all the cells in Selection use:

Public Sub Convert_To_Hyperlinks()
    Dim cell As Range
    Dim x As String
    Dim y As String
    Dim z As String
    Dim c As String

    For Each cell In Intersect(Selection, ActiveSheet.UsedRange)
        If cell <> "" Then
            c = cell.Value
            x = "=HYPERLINK(""[Five Ecom - Floor Plan.xlsm]Inventory!"" & ADDRESS(MATCH("""
            y = """, Inventory!$A$1:$A$2000,0),1),"""
            z = """)"
            cell.Formula = x & c & y & c & z
        End If
    Next
End Sub

(Assuming you need the content of each cell to be the "friendly name")

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