xxxxxxxxxx
Sub CreateDropdown()
Dim rng As Range
Dim ws As Worksheet
' Specify the worksheet where you want to add the dropdown
Set ws = ThisWorkbook.Worksheets("Sheet1")
' Specify the range where you want the dropdown to appear
Set rng = ws.Range("A1")
' Clear any existing data validation from the range
rng.Validation.Delete
' Set the data validation to allow a list using a dropdown
With rng.Validation
.Add Type:=xlValidateList, Formula1:="Option1,Option2,Option3"
.IgnoreBlank = True
.InCellDropdown = True
End With
End Sub
xxxxxxxxxx
Data > Data Validation
Allow: List
Source: Cell Range for valid options
in-cell drop-down: enabled by default
xxxxxxxxxx
import openpyxl
from openpyxl import Workbook
from openpyxl.worksheet.datavalidation import DataValidation
# Create a new workbook and select the active sheet
workbook = Workbook()
sheet = workbook.active
# Define the options for the drop-down list
options = ['Option 1', 'Option 2', 'Option 3']
# Create a DataValidation object for the drop-down list
dv = DataValidation(
type="list",
formula1='"{}"'.format(','.join(options))
)
# Add the DataValidation object to the first cell of the column where you want the drop-down list
sheet.add_data_validation(dv)
dv.add(sheet["A1"])
# Save the workbook
workbook.save("dropdown_list_example.xlsx")
xxxxxxxxxx
import openpyxl
from openpyxl import Workbook
from openpyxl.utils.dataframe import dataframe_to_rows
from openpyxl.worksheet.datavalidation import DataValidation
# Create a new workbook and select the active sheet
workbook = Workbook()
sheet = workbook.active
# Define the options for the drop-down list
options = ["Option 1", "Option 2", "Option 3"]
# Create a DataValidation object and set its properties
data_validation = DataValidation(
type="list",
formula1='"{}"'.format(",".join(options)), # Convert list to string
showDropDown=True,
showErrorMessage=True
)
# Apply the DataValidation object to a cell range
cell_range = "A1:A10" # Change to the desired range
sheet.add_data_validation(data_validation)
data_validation.add(sheet[cell_range])
# Save the workbook
workbook.save("output.xlsx")