Excel宏VBA基于活动单元格内容创建指向另一个工作表的超链接

时间:2016-05-14 10:42:07

标签: excel vba excel-vba hyperlink

我正在尝试创建一个链接到同一工作簿中基于单元格文本的另一个工作表中的单元格的超链接。我已尝试手动完成,结果如下:

    =HYPERLINK("[Five Ecom - Floor Plan.xlsx]Inventory!" & 
     ADDRESS(MATCH('8th'!F9,Inventory!$A$1:$A$2000,0),1),'8th'!F9)
  • '8th'!F9 - 是当前的单元格
  • Inventory!$A$1:$A$2000 - 单元格目的地的范围

友好文本将是同一当前单元格的内容。

我特别在字符串操作方面遇到困难,所以我决定将代码分成几个变量,到目前为止我无法生成所需的输出并导致运行时错误' 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

1 个答案:

答案 0 :(得分:1)

如果您替换了以下内容,您的宏将会起作用:

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

使用:

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

这假定 Match()找到它要查找的内容。

对于Selection中的所有单元格,使用:

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

(假设您需要每个单元格的内容为&#34;友好名称&#34;)