|
本帖最后由 cunfu2010 于 2016-4-7 21:13 编辑
想实现用VBA代码制作多级数据有效性下拉选项菜单,借鉴仿写现在实现了两级,后面的多次调试没有成功。求助:
1、现在的代码是不是不够精简?请帮忙精简一下。
2、如何实现多级目的,比如四级、五级等(工作中会用到)。
3、重新选择A列数据时,后面的数据全部清除,待选。
4、把A2实现改成A2:A100实现。
不用辅助表和辅助列(这种情况已经会做),只用代码,谢谢!!!
Private Sub Worksheet_Change(ByVal Target As Range)
Application.EnableEvents = False
On Error Resume Next
If Range("A2").Value <> "" Then
With Range("A2").Validation
.Delete
.Add Type:=xlValidateList, Formula1:="A,B,C"
End With
End If
If Target.Address = "$A$2" Then '一级数据有效性所在单元格为A2
If Target.Value <> "" Then
Dim i%, j(1 To 3) As String, a$
For i = 1 To 3
j(i) = Target.Value & i & ","
Next i
a = Left(Join(j), Len(Join(j)) - 1)
Else
a = "A1,A2,A3,B1,B2,B3,C1,C2,C3"
End If
If Range("B2").Value <> "" Then
With Range("B2").Validation
.Delete
.Add Type:=xlValidateList, Formula1:=a
End With
End If
If Range("B2").Value <> "" Then
With Range("B2").Validation
.Delete
.Add Type:=xlValidateList, Formula1:=a
End With
End If
If Target.Address = "$B$2" Then '二级数据有效性所在单元格为B2
If Target.Value <> "" Then
Dim m%, n(4 To 6) As String, b$
For m = 4 To 6
n(m) = Range("A2").Value & m & ","
Next m
b = Left(Join(n), Len(Join(n)) - 1)
Else
b = "A4,A5,A6,B4,B5,B6,C4,C5,C6"
End If
If Target = "A" Then
With Target.Offset(0, 1).Validation
.Delete
.Add Type:=xlValidateList, Formula1:="=A"
End With
End If
End If
End If
Application.EnableEvents = True
End Sub
做到4级,100行,单元格改变后,此单元格右边清空 - Private Sub Worksheet_Change(ByVal Target As Range)
- Application.EnableEvents = False
- If Intersect(Target, [a2:d100]) Is Nothing Then Exit Sub
- c = Target.Column
- If c < 4 Then Target.Offset(, 1).Resize(1, 4 - c) = ""
- Application.EnableEvents = True
- End Sub
- Private Sub Worksheet_SelectionChange(ByVal Target As Range)
- If Intersect(Target, [a2:d100]) Is Nothing Then Exit Sub
- c = Target.Column
- If c = 1 Then
- xstr = "A,B,C" '一级数据
- ElseIf c >= 2 Then '二三四级数据
- sj = Target.Offset(0, -1) '上一级
- If sj <> "" Then
- For i = 1 To 3
- xstr = xstr & "," & sj & i
- Next i
- xstr = Mid(xstr, 2)
- End If
- End If
- With Target.Validation
- .Delete
- .Add Type:=xlValidateList, Formula1:=xstr
- End With
- End Sub
复制代码
|
|