如何使用xlwings或pywin32为宏添加按钮

问题描述 投票:0回答:1

我想知道如何使用

xlwings
pywin32
添加宏按钮。

我找到了形状对象的方法(执行

test("shape")
),但是
test("button")
失败了,因为
sheet1.api.Buttons.Add
中出现无属性错误。

我只是实现了以下,因为当我在Excel录制宏中手动添加按钮时,我在VBA编辑器中发现了

ActiveSheet.Buttons.Add(288, 44.25, 151.5, 32.25).Select

import xlwings as xw
def test_button(obj_type):
    
    wb = xw.books.add()
    wb.save("test.xlsm")
    
    sheet1 = wb.sheets["Sheet1"]
    
    if obj_type == "shape":
        # Add Shape
        sheet1.api.Shapes.AddShape(1, 100, 50, 150, 30)
        
        shape_names = []
        for shape in sheet1.shapes:
            if shape.name not in shape_names:
                shape_names.append(shape.name)
                shape.characters.api.Text = "Shape Name = {}".format(shape.name)
                shape.api.OnAction = "sample_sub"
        print("shape names list:")
        print(shape_names)
    elif obj_type == "button":
        button = sheet1.api.Buttons.Add(288, 44.25, 151.5, 32.25) # FIXME
        button.api.OnAction = "sample_sub" # FIXME
        button.api.Text = "sample button" # FIXME
    else:
        raise ValueError("Invalid obj_type : {}".format(obj_type))
    
    return wb

sample_sub
定义为:

@xw.sub
def sample_sub():
    wb = xw.Book.caller()
    sheet1 = wb.sheets["Sheet1"]
    sheet1.range("A1").value = "This is a test message."
python python-3.x vba pywin32 xlwings
1个回答
0
投票

根据 MS 文档,没有名为 Buttons 的对象。 您可以使用创建一个按钮 FormControl,例如

sheet.api.Shapes.AddFormControl(0,1,1,1,1)
,请参阅 xlformcontrol 枚举

© www.soinside.com 2019 - 2024. All rights reserved.