我想让第二列中的所有行都成为下拉列表。用户单击单元格并选择任何现有名称。
怎么做?
当我运行此代码时,它显示错误:
无效或不合格的参考
Sub test()
Dim i As Integer
Dim OfficerList(4) As String
OfficerList(0) = "test1"
OfficerList(1) = "test2"
OfficerList(2) = "test3"
OfficerList(3) = "test4"
OfficerList(4) = "test5"
For i = Range("B5000").End(xlUp).Row To 2
Select Case VBA.CDate(Cells(i, 2))
.Delete
.Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, _
Operator:=xlBetween, Formula1:=Join(OfficerList, ",")
End Select
Next
For i = Range("C5000").End(xlUp).Row To 2 Step -1 'Range upto 5000, chnge this as per your requirment'
Select Case VBA.CDate(Cells(i, 3))
Case Is < VBA.Date()
Cells(i, 3).Interior.Color = vbGreen
Case Is = VBA.Date()
Cells(i, 3).Interior.Color = vbYellow
Case Is > VBA.Date()
Cells(i, 3).Interior.Color = vbRed
End Select
Next
End Sub
答案 0 :(得分:0)
这似乎不是Select Case
的正确位置:尝试使用此代替第一个循环
For i = Range("B5000").End(xlUp).Row To 2 Step -1
With Cells(i, 2).Validation
.Delete
.Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, Operator:=xlBetween, Formula1:=Join(OfficerList, ",")
End With
Next i
我只使用Select Case
而不是With
,并确保指定您正在更改单元格的验证条目,并且我将循环更改为包含Step -1
(喜欢你的第二个循环)。
答案 1 :(得分:0)
看看这个。我也把你的循环结合起来了。不确定为什么你会向后运行它,但我已经离开了它
Sub test()
Dim i As Long
Dim OfficerList(4) As String
OfficerList(0) = "test1"
OfficerList(1) = "test2"
OfficerList(2) = "test3"
OfficerList(3) = "test4"
OfficerList(4) = "test5"
' Update this with your sheet
With Sheet1
For i = .Range("B5000").End(xlUp).Row To 2 Step -1
With .Cells(i, 2).Validation
.Delete
.Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, _
Operator:=xlBetween, Formula1:=Join(OfficerList, ",")
End With
Select Case VBA.CDate(.Cells(i, 3))
Case Is < VBA.Date()
.Cells(i, 3).Interior.Color = vbGreen
Case Is = VBA.Date()
.Cells(i, 3).Interior.Color = vbYellow
Case Is > VBA.Date()
.Cells(i, 3).Interior.Color = vbRed
End Select
Next i
End With
End Sub