超链接列= Excel宏

时间:2015-02-06 03:17:50

标签: excel excel-vba vba

我在一个文件夹中有很多pdfs和excel表。命名顺序是一致的。

Sheet将被命名为Apple。 Pdfs将命名为Apple_1,Apple_2

我想要一个excel宏工作 获取活动工作表名称。 超链接G列中的单元格。 当我单击单元格1中的文本时,它应该打开Apple_1.pdf 当我单击单元格2时,它应该打开Apple_2.pdf。 这应该继续,直到文本填充该列中的单元格。

我有一个相同的Word宏,但我不知道如何使它在Excel中工作。下面是宏观。

Sub macro3()
Dim tbl As Table
Dim coll As Column
Dim path As String
Dim pdf As String
Dim path1 As String
pdfname = ActiveDocument.Name
pdfname = Left(pdfname, Len(pdfname) - 4)
pdfname = Replace(pdfname, " ", "_")
Set tbl = ActiveDocument.Tables(1)
Set coll = tbl.Columns(7)
Set colpdf = tbl.Columns(7)
i = 0
For Each c In coll.Cells
If (i <> 0 And InStr(c, ".pdf") > 0) Then
path1 = pdfname & "_" & i & ".pdf"
ActiveDocument.Hyperlinks.Add Anchor:=c.Range, Address:=path1
End If
i = i + 1
Next
End Sub

1 个答案:

答案 0 :(得分:1)

设置path1时,您缺少文档的目录路径。当您单击超链接以打开其查找&#34; Apple1.pdf&#34;的目录时这不是一个有效的文件路径。您只需要将路径开头的目录路径添加到&#34; C:\ MyPath \ Apple1.pdf&#34;。 你的代码:

pdfname = ActiveDocument.Name
pdfname = Left(pdfname, Len(pdfname) - 4)
pdfname = Replace(pdfname, " ", "_")
path1 = pdfname & "_" & i & ".pdf"

解决方案1:假设文档与activedocument位于同一文件夹中。

Dim MyPath as string
MyPath = ActiveDocument.Path
path1 = MyPath & "\" & pdfname & "_" & i & ".pdf"

解决方案2:文件位于另一个位置,您可以添加另一个字符串地址。

Dim MyPath as string
MyPath = "C:\MyOtherLocation"
path1 = MyPath & "\" & pdfname & "_" & i & ".pdf"
相关问题