在剪贴板中添加文本作为单元格的超链接

时间:2015-10-12 06:41:10

标签: excel vba excel-vba

我想创建一个宏,在运行时,将剪贴板中包含的链接粘贴到当前单元格作为超链接。我尝试使用记录宏生成以下代码,我对其进行了一些修改:

Sub Macro1()
'
' Macro1 Macro
'

'
    ActiveSheet.Hyperlinks.Add Anchor:=Selection, Address:="abc.com" _
        , TextToDisplay:="Link"
End Sub

在这里,代替abc.com,它应该是"粘贴键盘中的文字"。

1 个答案:

答案 0 :(得分:0)

根据@DanL评论,这是您需要的代码:

Sub Macro1()
    ActiveSheet.Hyperlinks.Add Anchor:=Selection, Address:=GetClipboardText() _
        , TextToDisplay:="Link"
End Sub

Function GetClipBoardText() as String
   Dim DataObj As MSForms.DataObject
   Set DataObj = New MsForms.DataObject '<~~ Amended as per jp's suggestion

   On Error GoTo Whoa

   '~~> Get data from the clipboard.
   DataObj.GetFromClipboard

   '~~> Get clipboard contents
   GetClipBoardText = DataObj.GetText(1)


   Exit Sub
Whoa:
   If Err <> 0 Then MsgBox "Data on clipboard is not text or is empty"
End Sub