我的脚本中有两个列表框,其中填充了Month值和Year值。如果列表框中填充了值,则会将它们写入工作表,而如果它们为空,则应该抛出错误。
我创建了一个测试场景,其中有两个空白列表框,下面的代码应该抛出一个消息框,建议用户在执行脚本之前选择一个值。但是,VBA有自己的想法,并认为列表框中填充了值,因此我得到:
运行时错误1004 - 无法获取DropDown类的List属性
下面的代码是否有问题,我没有看到?
Sub TestDropDown()
Dim MonthBox As DropDown, YearBox As DropDown
Dim WB As Workbook
Dim WS4 as Worksheet
Set WB = ThisWorkbook
Set WS4 = WB.Worksheets("Config")
Set MonthBox = ThisWorkbook.Worksheets("Control Sheet").DropDowns("Drop Down 8")
Set YearBox = ThisWorkbook.Worksheets("Control Sheet").DropDowns("Drop Down 9")
'Check Monthbox for values
If IsNull(MonthBox.Value) Then
MsgBox ("Select a Month before running the script")
Failvalue = 1
GoTo EndSub:
Else
WS4.Cells(2, 9).Value = MonthBox.List(MonthBox.Value)
End If
'Check Yearbox for values
If IsNull(YearBox.Value) Then
MsgBox "Please select a Year before running the script", vbExclamation
Failvalue = 1
GoTo EndSub:
Else
WS4.Cells(2, 10).Value = YearBox.List(YearBox.Value)
End If
EndSub:
If Failvalue = 0 Then
MsgBox ("Process complete")
Else
MsgBox "Process failed to complete", vbCritical
End If
WS4.Visible = xlSheetHidden
End Sub
答案 0 :(得分:0)
您应该检查.ListIndex
而不是.Value
。如果ListIndex返回零,则表示没有选择。
试试这个:
Sub TestDropDown()
Dim MonthBox As DropDown, YearBox As DropDown, Failvalue As Integer
Dim WB As Workbook
Dim WS4 As Worksheet
Set WB = ThisWorkbook
Set WS4 = WB.Worksheets("Config")
Set MonthBox = ThisWorkbook.Worksheets("Control Sheet").DropDowns("Drop Down 8")
Set YearBox = ThisWorkbook.Worksheets("Control Sheet").DropDowns("Drop Down 9")
'Check Monthbox for values
'If IsNull(MonthBox.Value) Then
If MonthBox.ListIndex = 0 Then
MsgBox ("Select a Month before running the script")
Failvalue = 1
GoTo EndSub:
Else
WS4.Cells(2, 9).Value = MonthBox.List(MonthBox.ListIndex)
End If
'Check Yearbox for values
'If IsNull(YearBox.Value) Then
If YearBox.ListIndex = 0 Then
MsgBox "Please select a Year before running the script", vbExclamation
Failvalue = 1
GoTo EndSub:
Else
WS4.Cells(2, 10).Value = YearBox.List(YearBox.ListIndex)
End If
EndSub:
If Failvalue = 0 Then
MsgBox ("Process complete")
Else
MsgBox "Process failed to complete", vbCritical
End If
WS4.Visible = xlSheetHidden
End Sub
答案 1 :(得分:-1)
看起来下面一行代码不够,因为列表框值不等于null。
If IsNull(YearBox.Value) then
如果在列表框值上运行msgbox,它在空白列表框中返回0,所以我将代码更改为以下
If YearBox.Value = 0 then
这很好用!