这是我的代码,可以完全按照您的要求进行操作。
我已将独立列定义为命名范围Major_Category
,并将下拉验证设置为数据列表。然后,我有几个其他名为 的数据列表cat_subItems
。因此,对于您的示例,主要类别将包含项目
然后我定义了更多的列表,称为
其中将包含水果或蔬菜的名称。然后根据主要类别选择,Worksheet_change 事件会将下一列中的下拉验证更改为cat_fruit
或cat_vegetable
。
注意:如果您使用的是 excel 的保护工作表,则此代码效果不佳。请参阅此问题以处理 Excel 的工作表/书籍保护。
Public Sub Worksheet_Change(ByVal target As Range)
On Error GoTo ErrHandler:
Dim VRange As Range, cell As Range
Dim msg As String
Dim validateCode As Variant
Dim modCell As Range
Set VRange = Range("Major_Category")
If Intersect(VRange, target) Is Nothing Then Exit Sub
For Each cell In Intersect(VRange, target)
b = cell.Value
curRow = target.Row
Set modCell = cell.Offset(0, 1) 'cell to modify the validation'
If Not (b = "") Then
modCell.Validation.Delete
modCell.Validation.Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, Operator:= _
'sets the validation formula to the list/range name'
xlBetween, Formula1:="=cat_" & b
modCell.Validation.IgnoreBlank = True
modCell.Validation.InCellDropdown = True
modCell.Validation.InputTitle = ""
modCell.Validation.ErrorTitle = ""
modCell.Validation.ErrorMessage = ""
modCell.Validation.ShowInput = True
modCell.Validation.ShowError = True
End If
Next cell
Cleanup:
Exit Sub
ErrHandler:
MsgBox Err, vbOKOnly, "Error Occurred"
Resume Cleanup:
End Sub