简体   繁体   中英

Create a Drop down list using XLWings in Python

I have tried this code, but this is for validation. I want a code to create a new drop down menu.


    app = xw.App(visible=True)
    wb = app.books.open('Test.xlsx')
    sht = wb.sheets['Sheet1']
    Formula1='"Dog,Cat,Bat"'
    dv = sht.range('A1').api.Validation.Formula1

I have tried using openpyxl it is working but it doesn't save a file when the file is open.

xlwings is a wrapper of win32com , which is similar to VBA. With recording VBA macro for reference, the following code should work.

import xlwings as xw

app = xw.App(visible=True)
wb = app.books.open('Test.xlsx')
sht = wb.sheets['Sheet1']
Formula1='Dog,Cat,Bat' # remove the redundant "


# set up validation
sht.range('A1').api.Validation.Add(Type=3, Formula1=Formula1)

The exploring steps:

Record a macro for the default steps to create a list type data validation:

Sub Macro1()
'
' Macro1 Macro
'

'
    Range("A1").Select
    Application.WindowState = xlMaximized
    With Selection.Validation
        .Delete
        .Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, Operator:= _
        xlBetween, Formula1:="Dog,Cat,Bat"
        .IgnoreBlank = True
        .InCellDropdown = True
        .InputTitle = ""
        .ErrorTitle = ""
        .InputMessage = ""
        .ErrorMessage = ""
        .ShowInput = True
        .ShowError = True
    End With
End Sub

Indeed, we did only two key steps and kept the rest default:

  • select List from validation criteria dropdown list
  • type the source for list

So, the above code should be simplified as

' VBA
Range("A1").Validation.Add Type:=xlValidateList, Formula1:="Dog,Cat,Bat"

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