Excel函数在超链接公式中作为“链接位置”在写入时被调用

2024-09-27 07:23:13 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用XLWINGS为Excel添加一些功能。我希望能够使用特定的音频播放器和特定的编解码器播放音频文件时,在excel单元格中的超链接被单击时(而不是当超链接公式写入其单元格时)。在

xlwings自定义项是:

@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用于编写指向excel的超链接的代码是:

^{pr2}$

我也试过:

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

编写的excel超链接如下所示:

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

这很管用,但我有一个不受欢迎的行为:

  1. 每次xlwings将此公式写入单元格时,超链接公式引用的play_audio()代码都将执行(这意味着播放音频并限制写入过程)。我希望excel在用户单击超链接时计算公式,但它似乎是由保存、关闭或工作簿中的其他事件触发的。在

我审阅了this特定的帖子,并审阅了this参考页,但我希望尽可能避免用VBA编写解决方案,并在同一py文件中保持所有代码的一致性。在

有什么想法吗?在

谢谢!在


Tags: oftheto代码playas音频xlwings

热门问题