从Excel VBA中的单元格内容创建超链接

时间:2016-04-22 14:33:34

标签: excel vba excel-vba excel-2010

我正在尝试根据用户选择的单元格区域中的单元格内容创建超链接。我已经做到这一点,但是当它运行时它循环循环但不会创建任何超链接。

Sub AcctHyperlink()
    Dim WorkRng As Range
    On Error Resume Next
    Set WorkRng = Application.Selection
    Set WorkRng = Application.InputBox("Range", "Select Range", WorkRng.Address, Type:=8)

    For i = WorkRng.Rows.Count To 1 Step -1
        If WorkRng.Cells(i, 1).Value <> "" Then

            WorkRng.Cells(i, 1).Hyperlink.Add Anchor:=WorkRng.Cells(i, 1), _
            Adress:="https://example.com/" & WorkRng.Cells(i, 1).Value & "/search", _
            TextToDisplay:=WorkRng.Cells(i, 1).Value

        End If
    Next
End Sub

2 个答案:

答案 0 :(得分:1)

已修改只有两个错别字和CStr()次来电! Hyperlink应为HyperlinksAdress应为Address。您编译的代码很好,因为Range.Item返回Variant而不是Range,因此Excel无法在编译时标记此类错误。以下适用于我的Excel 2013安装:

Option Explicit    '<--- always use this for more robust code

Sub AcctHyperlink()
    Dim WorkRng As Range
    'On Error Resume Next  '<--- Omit for error checking
    Set WorkRng = Application.Selection
    Set WorkRng = Application.InputBox("Range", "Select Range", WorkRng.Address, Type:=8)

    Dim i as Long   '<--- Need this because of Option Explicit
    Dim addr as String  '<--- ditto
    For i = WorkRng.Rows.Count To 1 Step -1
        If WorkRng.Cells(i, 1).Value <> "" Then
            addr = "https://insight.metavante.org/opstopb1/OpstopServlet/Search?activityID=ViewProfileLnNote&activityType=note&activityTrgtID=undefined&activityAction=search&profileView=&accountNumber=" & CStr(WorkRng.Cells(i, 1).Value) & "&accountType=&subAccountNumber=&prcsGrpID=136&RelatedFIs=136&searchBy=account"
                ' Note: need CStr()
            '                            V--- "Hyperlinks"
            WorkRng.Cells(i, 1).Hyperlinks.Add Anchor:=WorkRng.Cells(i, 1), _
            Address:=addr, _
            TextToDisplay:=CStr(WorkRng.Cells(i, 1).Value)
            '^--- "Address" two lines up
            '              ^^^^---- Need CStr()
        End If
    Next
End Sub

答案 1 :(得分:0)

你必须改变:

AdressAddress的{​​p> Hyperlink Hyperlinks的{​​{1}}