使用 python 的 xlwings

我遇到了这个我无法弄清楚的问题:我正在尝试使用 xlwings 库将一些 VB 代码转换为 Python。我试图转换的行如下:

Ttarget = Worksheets('Main').txtTmaxTarget.Value  'This is VB code

因此,在 Excel 工作簿中是一个名为“Main”的工作表,其中包含一个文本框,该文本框是从开发人员功能区 -> 插入 -> active X 控件 -> 文本框插入的。该文本框的名称(在属性中)是 txtTmaxTarget。

VB 中的代码有效,但无法让 Python xlwings 访问 TextBox 内的文本(工作表中的 TextBox 不为空)。这是我得到结果的最接近的猜测:

import xlwings as xw

@xw.sub
def mySub(): 
    Ttarget = xw.Book.caller().sheets('Main').shapes('txtTmaxTarget').text

但这失败了,因为无论我在 TextBox 中放入什么,Ttarget 在返回时始终为 None。访问 TextBox 内容的正确方法是什么?

iffta 回答:使用 python 的 xlwings

这个是阅读原文:

import xlwings as xw
def print_text_box():
    book_name = r'C:\hardcoded-path\foo.xlsx'
    sheet_name = 'Main'
    wb = xw.Book(book_name)
    sht = wb.sheets[sheet_name]
    my_text = wb.sheets('Main').api.OLEObjects("TextBox1").Object.Value
    print(my_text)
print_text_box()

书写方式相同:

wb.sheets('Main').api.OLEObjects("TextBox1").Object.Value = "some random text"

本文链接:https://www.f2er.com/286156.html

大家都在问