简体   繁体   中英

Hyperlink Columns = Excel Macro

I have many pdfs and an excel sheet in one folder. The naming sequence is consistent.

Sheet will be named Apple. Pdfs will be named Apple_1, Apple_2

I want an excel macro to work Get the active sheet name. Hyperlink the cells in G column. When I click on text in cell 1, it should open Apple_1.pdf When I click on cell 2, it should open Apple_2.pdf. This should continue until text filled cells in that column.

I have a Word macro for the same, but I don't know how to make it work in excel. Below is the word macro.

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

You are missing the directory path to the documents when setting path1. When you click the hyperlink to open its looking in a directory for "Apple1.pdf" which isn't a valid file path. You just need to add the directory path to the start of the path should look like "C:\\MyPath\\Apple1.pdf". Your code:

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

Solution1: Assuming the documents are in the same folder as activedocument.

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

Solution2: Files are in another location you can add another string address.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM