【问题标题】:Excel button click event in PythonPython中的Excel按钮单击事件
【发布时间】:2020-11-29 19:39:48
【问题描述】:

我正在使用 pywin32 在 Python 和 Excel 之间建立连接,并且开始处理事件。碰巧在我正在使用的项目中,我需要在 Python 中捕获一个按钮单击事件。我从 Workbooks 和 Worksheets 中看到了事件,但我无法确定点击事件。

class WorkbookEvents:

    def OnSheetSelectionChange(self, *args):
        #print(args)
        print("You changed the selection")
        #print(args[1].Address)
        #args[0].Range("A1").Value = "Range :" + str(args[1].Address)

workbook_events= WIN32.WithEvents(wb, WorkbookEvents)

【问题讨论】:

    标签: python excel com pywin32


    【解决方案1】:

    很晚才得到答案,但我得到了它使用这段代码(并使用 Excel 中的 ActiveX“命令按钮”控件)

    import win32com.client as win32
    import pythoncom    
    import sys
    import time
    
    #The event handlers container
    class wsEvents:
        def OnClick(self,*args):
            print('Button Clicked')
    
    
    xlApp = win32.Dispatch("Excel.Application")
    xlwb = xlApp.Workbooks("Book1.xlsm")
    ws=xlwb.Sheets("Sheet1")
    xl_events=win32.WithEvents(ws.OLEObjects("CommandButton1").Object,wsEvents)
    
    # define initalizer
    keepOpen = True
    
    while keepOpen:
    
        time.sleep(0.1)
        # display the message
        pythoncom.PumpWaitingMessages()
    
        try:
    
            # if the workbook count does not equal zero we can assume Excel is open
            if xlApp.Workbooks.Count != 0:
                keepOpen = True
    
            # otherwise close the application and exit the script
            else:
                keepOpen = False
                xlApp = None 
                sys.exit()
    
        except:
            # if there is an error close excel and exit the script
            keepOpen = False
            xl = None
    

    ActiveX 命令按钮作为“独立”COM(OLE) 对象加载到 Excel 中,该对象由显示它的工作表引用。 Excel API 允许以explained here 形式获取对 OLE 对象的引用,并且可以在 python 代码中轻松完成。

    基本上,事件处理程序不是由工作表管理,而是由命令按钮对象管理,当然,命令按钮支持的事件是 OnClick 等......结果证明解决方案很优雅,win32com 非常尊重对于 COM :)

    必须将他的 sn-p 归功于 Alex Reed blog,以使 python 脚本等待新事件。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-03-08
      • 2011-11-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-02-17
      • 1970-01-01
      相关资源
      最近更新 更多