强制超链接在记事本中打开目标文件

时间:2012-07-17 15:37:30

标签: excel vba excel-vba hyperlink

我有一个脚本可以抓取某个文件夹中的所有文件并列出该文件夹中的所有文件。然后它会创建一个链接,从Excel内部打开这些文件。我想知道是否有办法将它放在一个shell中,以便文件只在记事本中打开。我现在使用的代码是:

Sub MakeLink(ByVal cell As Range, ByVal url As String, ByVal txt As String, ByVal tooltip_text As String)
        ActiveSheet.Hyperlinks.Add _
            Anchor:=cell, _
            Address:=url, _
            ScreenTip:=tooltip_text, _
            TextToDisplay:=txt
    End Sub

Sub Portfolios()

    Range("A1:Z200").Clear
    Dim objFSO As Object
    Dim objFolder As Object
    Dim objFile As Object
    Dim ws As Worksheet
    Range("A3").Font.Bold = True


    Set objFSO = CreateObject("Scripting.FileSystemObject")
    Set ws = Worksheets("Library")


     'Get the folder object associated with the directory
    Set objFolder = objFSO.GetFolder("C:\Portfolios")
    ws.Cells(3, 1).Value = "The files found in " & objFolder.Name & " are:"

     'Loop through the Files collection
    For Each objFile In objFolder.Files
        'ws.Cells(ws.UsedRange.Rows.Count + 3, 2).Value = objFile.Name
        MakeLink ws.Cells(ws.UsedRange.Rows.Count + 3, 2), objFile, objFile.Name, objFile.Name

    Next

     'Clean up!
    Set objFolder = Nothing
    Set objFile = Nothing
    Set objFSO = Nothing
End Sub

我知道我必须按照MakeLink = Shell("C:\WINDOWS\notepad.exe", 1)的方式做一些事情,但我似乎对于它适合的地方有点麻烦。

谢谢, ˚F

1 个答案:

答案 0 :(得分:1)

文件将以文件类型的默认程序打开。

如果你想强制它们在记事本中打开,那么你将不得不编写一些代码来处理Worksheet_FollowHyperlink事件:你可以从Target参数获取单元格文本并从那里弹出记事本。

为防止超链接将用户带到其他地方,只需将目标地址设置为与包含超链接的单元格相同的单元格。

Private Sub Worksheet_FollowHyperlink(ByVal Target As Hyperlink)

    Dim fPath As String, res

    fPath = Target.TextToDisplay
    res = Shell("notepad.exe """ & fPath & """", vbNormalFocus)

End Sub

创建超链接:

Sub MakeLink(rng As Range, txt As String)
    Dim addr As String

    addr = "'" & rng.Parent.Name & "'!" & rng.Address(False, False)
    rng.Parent.Hyperlinks.add Anchor:=rng, Address:="", _
                     SubAddress:=addr, TextToDisplay:=txt

End Sub