最近使用xlwings庫去在excel中創建下拉菜單,但是發現一個問題,生成下拉菜單的單元格,不能輸入下拉菜單之外的字符,否則就會有彈窗報錯
img1.png
盡管設置了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相關,手動把這個對號勾掉,就也能正常寫入值了
img2.png
但是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處的對勾不見了