简体   繁体   中英

Is it possible to get a Drop down of options in User Defined Function (UDF) using Python xlwings library?

I am trying to create a User defined function (UDF) using python xlwings library to recall price of the product. I have a list of 299 products, remembering name of all the products is not possible.

I am trying to create an UDF like below to get the price of the product:

=ProductPrice(Name_of_Product) *#this will be used in excel cell*

Here, I want a drop down of all my 299 products to choose one from the list. Something like below:

在此处输入图像描述

I can not see any help on this available on internet.

Is it possible to achieve this? if yes, can you please guide?

I'm not sure if it can be done with Excel-DNA/IntelliSense or something like that. But it can be done with Excel itself.

As far as you're talking about a list of products, I assume you have this list in a python code. So I suggest to create a new sheet with products in one row. Convet them into table (ListObject), with products as a column names . Put corresponding prices (or a function like =CalculatePrice(@ProductPrice[#Headers]) under each product in a single row of this table. Name this table ProductPrice . And voila! Whenever you print in a cell =ProductPrice[ a dropdown list of your products appears. You select a product, close the square bracket and get the price of the product.

Here's a visual how it can look:

图片

Let's see how it can be done programmaticaly:

import xlwings as xl
from pathlib import Path

products = '''
Scented Candles
Portable Projector
Bluetooth Speaker
Smart Watch
Vegetable Chopper
Neck Massager
Ice Skates
Back Cushion
Portable Blender
Nail Polish
'''

products = products.split("\n")[1:-1]

def CalculatePrice(product: str) -> float:
    'Some function to calculate the price of the product'
    return len(product)

f = Path('test_products.xlsx')
if f.exists():
    f.unlink()    # remove the old file if exists

wb = xl.Book()
sh = wb.sheets.add("PriceList")
sh.range((1,1), (1,len(products))).value = products
sh.range((2,1), (2,len(products))).value = [*map(CalculatePrice, products)]
# create a table (a.k.a. ListObject) by name ProductPrice
sh.tables.add(sh['A1'].current_region, 'ProductPrice').show_autofilter = False
sh.visible = 2   # https://docs.microsoft.com/en-us/office/vba/api/excel.xlsheetvisibility

wb.save()
wb.close()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM