最近使用xlwings库去在excel中创建下拉菜单,但是发现一个问题,生成下拉菜单的单元格,不能输入下拉菜单之外的字符,否则就会有弹窗报错
尽管设置了app.display_alerts = False,没有报错弹窗了,但是输入的内容依然无法作为单元格的值,填写进去
代码如下:
import xlwings as xw
# 打开 Excel 文件
app = xw.App(visible=True, add_book=False)
wb = app.books.open(r"New Microsoft Excel Worksheet.xlsx")
app.display_alerts = False
# 获取需要设置下拉菜单的单元格
sheet = wb.sheets.active
cell = sheet.range('A1')
from xlwings import constants
cell.api.Validation.Delete()
validation_list = "AAA,BBB,CCC,DDD"
dv_type = constants.DVType.xlValidateList
dv_alertstyle = constants.DVAlertStyle.xlValidAlertStop
dv_operator = constants.FormatConditionOperator.xlBetween
cell.api.Validation.Add(dv_type, dv_alertstyle, dv_operator, validation_list)
cell.api.Validation.IgnoreFailure = True
后来发现这个现象和数据校验中的Error Alert相关,手动把这个对号勾掉,就也能正常写入值了
但是xlwings的api.Validation.Add()方法中并没有参数支持设置这个地方,所以就曲线救国,借助VBA在单元格被点击的时候,去除Error Alert,实现了想要的效果,VBA代码如下:
Sub GetClickedCell()
Dim selectedCell As Range
If TypeName(Selection) <> "Range" Then
Exit Sub
End If
If Selection.Cells.Count > 1 Then
Exit Sub
End If
If Not Selection.Validation Is Nothing Then
Set selectedCell = Selection.Cells(1)
selectedCell.Validation.IgnoreBlank = True
Selection.Validation.ShowError = False
' MsgBox selectedCell.Address
End If
End Sub
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
' A1:A1048576表示需要设置去除下拉菜单数据校验警告的单元格区域
If Not Intersect(Target, Me.Range("A1:A1048576")) Is Nothing Then
Call GetClickedCell
End If
End Sub
按ALT+F11, 把上面这段代码贴进去,保存后,点击之前设置了数据校验的单元格,就可以发现Error Alert处的对勾不见了