首页 > 解决方案 > Xlwings + Pygatt:将对象从 Pygatt 存储到 Excel VBA

问题描述

我能够使用 xlwings 在 VBA 代码和 Python UDF 之间发送接收数据。

我在 Python UDF 中使用 Pygatt 与 BLE 设备进行通信。

我将信息存储在 Excel 中的一张工作表中,并根据需要在 Python UDF 中访问它。

我的问题是,我无法存储适配器的值并在另一个 UDF 中使用:-

adapter = pygatt.BGAPIBackend(serial_port=str(comPort))
adapter.start()

我的想法是将适配器值存储在 Excel 工作表中的一个单元格中,然后在另一个 UDF 中访问它。

以下是我的UDF:-

#Function to open BLE connection based on the comport number
@xw.func
@xw.sub
def ComPortSelect(strP):
    wb = xw.Book.caller()
    comPort = str(strP)
    comPort = 'COM'+comPort
    adapter = pygatt.BGAPIBackend(serial_port=str(comPort))
    adapter.start()
    listOfDevices = adapter.scan()
    wb.sheets['Sheet1'].range('A1').value = adapter  **<----- Gives error**

将对象保存在 Excel 单元格错误中

#Function to use the *adapter* and execute other Pygatt functions
@xw.func
@xw.sub
def ConnectToSelectedDevice(device):
    adapter =  wb.sheets['Sheet1'].range('A1').value  **<--**
    deviceHandle = adapter.connect(device)
    .
    .
    .

我如何存储所需的对象并在其他 UDF 中使用它?有没有其他正确的方法来实现这一目标?

非常感谢提前!!!

标签: user-defined-functionsxlwings

解决方案


我使用全局变量并在 Python UDF 之间共享它。

我继续使用这个解决方案。


推荐阅读