Excel function as "Link_Location" in HYPERLINK formula called on write

I am using XLWINGS to add some functionality to Excel. I want to be able to use a specific audio player with specific codecs to play audio files when clicking on a hyperlink in an excel cell (not when the hyperlink formula is written into its cell).

Xlwings UDF:

@xw.func(volatile=False)
def play_audio(audiofilepath):
    '''
    Use the audioplayer defined at the top of the module as a
    path to an executable to 
    open the audiofile. The audioplayer auto-closes when the 
    reproduction of the audio file is complete as the timeout 
    parameter is equal to the calculated duration of the file
    '''
    #Get file length in seconds
    with contextlib.closing(wave.open(audiofilepath,'r')) as f:
        frames = f.getnframes()
        rate = f.getframerate()
        length = frames / float(rate)
        '''
        Use the defined audioplayer to play the file and 
        close out the app after the files duration
        '''
        try:
            subprocess.run([audioplayer,audiofilepath], timeout = length)
        except:
            pass

      

XLWINGS code uses excel hyperlinks to write:

write_cell.value = '=HYPERLINK(play_audio("{}"),"OK")'.format(fullpathandfilename)

      

I've also tried:

write_cell.add_hyperlink(address =  '=play_audio("{}")'.format(fullpathandfilename),text_to_display ="OK",screen_tip=fullpathandfilename)

      

The excel hyperlink looks like this:

=HYPERLINK(play_audio("path\to\audio.wav"),"PLAY")

      

This works, but I have unwanted behavior:

  • Each time xlwings writes this formula to the cell, the play_audio () code is executed, which is referenced by the HYPERLINK formula (meaning the sound is playing and the bottle is being recorded). I want Excel to evaluate the formula when the user clicks on the hyperlink, but it seems to be triggered by other events like save, close, or other events in the workbook.

I've reviewed this particular post and reviewed this page , but I want to avoid having to code the solution in VBA if at all possible and keep the coherent code in the same py file.

Any ideas?

Thank!

+3


source to share





All Articles