Shankar Kumar Shankar Kumar - 3 years ago 168
Python Question

Error when using Python to create hyperlink within a worksheet in Excel

I am trying add hyperlinking functionality in my Excel documents by being able to click on a cell and it will take me to another part of the Excel document. I have code below that should take me to cell A21 when I click on A1. The code executes fine, but when I click on the link, a window pops up saying "Cannot open the specified file." Is there a problem with the way I'm referencing the cell? Or is there a better way to accomplish this?

from win32com.client import Dispatch
excel = Dispatch('Excel.Application')

def main():

def CreateLink():
cell_location = excel.Worksheets(1).Cells(1,1)
cell_destination = excel.Worksheets(1).Cells(21,1)
cell_text = "Cell A21"
excel.Worksheets(1).Hyperlinks.Add(Anchor=cell_location, Address=cell_destination, TextToDisplay=cell_text)

if __name__ == '__main__':

Answer Source

Try this:

def CreateLink():
    excel.Worksheets(1).Cells(1,1).Value = '=HYPERLINK(A21,"Cell A21")'
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download