使用vba向名称添加超链接

时间:2015-04-18 10:04:26

标签: excel vba excel-vba hyperlink

我的VBA技能不存在,我无法找到任何适合我情况的线程,因此这个帖子。

我在包含名称的Excel工作表中有一列(B列),我试图将B中的单元格超链接到网页。每行有一个特定的网页。

如果我有一个包含所有相应网址的列,但是问题是电子表格的最终版本没有包含网址的列,则可以很容易地使用HYPERLINK功能。

最终版本将包括哪些内容: (列B)超链接到特定网页的名称,和 (A列)包含URL的唯一部分加上B

中的名称的ID

除最后的数字外,网址都相同。 不会改变的部分是:

http://www.regulations.gov/#!documentDetail;D=CFPB-2011-0008

并且每个网址的末尾都有一个四位数字。

以" CFPB"开头的位以四位数字结尾的部分将包含在A列中。

所以我的计划是编写一个VBA程序,使用

构造的URL向B添加超链接
http://www.regulations.gov/#!documentDetail;D=

和A中相应细胞的前部(例如CFPB-2011-0008-0002)。我正在考虑使用LEFT函数从A获取URL的第二部分(例如LEFT(A1,19))。

很抱歉,如果说明不明确......将非常感谢任何帮助。

3 个答案:

答案 0 :(得分:2)

我正确理解了这个问题,您可以使用简单的工作表函数来完成此操作。只需将URL连接在一起:

=HYPERLINK(CONCATENATE("http://www.regulations.gov/#!documentDetail;D=",LEFT(A1,14)))

只需将URL添加到现有文档名称的一个VBA解决方案就像:

Sub AddHyperlinks()

    Dim url As String

    Dim current As Range
    For Each current In Selection.Cells
        url = "http://www.regulations.gov/#!documentDetail;D=" & _
              Left$(current.Value, 14)
        current.Worksheet.Hyperlinks.Add current, url
    Next current

End Sub

选择要添加超链接的单元格并运行宏。

答案 1 :(得分:0)

我前几天把一个脚本放在一起做类似的事情,你想把它放到一个循环或其他东西中来浏览电子表格中的列表。我使用iCurrentRow和iCurrentCol来导航我的工作表。

使用您建议的函数在您想要的单元格中构建超链接字符串,即B列中的单元格,然后将strString设置为此值。我刚刚添加了strString(尚未经过测试),所以如果它不起作用,那么你可能需要在CStr()中包含它。

无论如何,它应该给你一些工作。

' Set the string to the hyperlink address    
strString = Cells(iCurrentRow, iCurrentCol).value
' Check if the cell already has a hyperlink
If Cells(iCurrentRow, iCurrentCol).Hyperlinks.Count > 0 Then
    'If it does then check if it is the same as in the cell
     If strString  <> CStr(Cells(iCurrentRow, iCurrentCol).Hyperlinks(1).Address) Then
         'Check if there is no new hyperlink
          If strString = "" Then
              Cells(iCurrentRow, iCurrentCol).Hyperlinks.Delete
          Else
              ActiveSheet.Hyperlinks.Add Anchor:=Cells(iCurrentRow, iCurrentCol), _
                  Address:=strString
          End If
      End If
Else
    'If there isn't an existing hyperlink then add it
     If strString <> "" Then
         ActiveSheet.Hyperlinks.Add Anchor:=Cells(iCurrentRow, iCurrentCol), _
             Address:=strString 
     End If
End If

答案 2 :(得分:0)

尝试一下:

Sub MAIN()
    Dim rng As Range, rr As Range, r As Range
    Set rng = Intersect(Range("B:B"), ActiveSheet.UsedRange)

    For Each rr In rng
        If rr.Value <> "" Then
            Set r = rr
            Call hyper_maker(r)
        End If
    Next rr
End Sub

Sub hyper_maker(r As Range)
    If r.Hyperlinks.Count > 0 Then
        r.Hyperlinks.Delete
    End If
    txt = r.Value
    s = "http://www.regulations.gov/#!documentDetail;D=" & txt
    r.Value = s
    r.Select
    Application.SendKeys "{F2}"
    Application.SendKeys "{ENTER}"
    DoEvents
    r.Hyperlinks(1).TextToDisplay = txt
End Sub
相关问题