|
为了更方便扩展菜单层数,把字典设置改为循环:
- Sub CreatMe() '一个字典生成左键四级树型菜单
- Dim d As Object, i&, j&, k, k2, t2, a3, l&, arr, s$
- Set d = CreateObject("scripting.dictionary")
- arr = Sheets("Sheet1").Range("A1").CurrentRegion
- For i = 2 To UBound(arr)
- s = arr(i, 1)
- If InStr(d(s) & ",", "," & arr(i, 2) & ",") = 0 Then d(s) = d(s) & "," & arr(i, 2) '字典键值是一级菜单,字典条目是二级菜单
- For j = 2 To 3 '从第二级到倒数第二级菜单
- If Len(arr(i, j)) = 0 Then Exit For '从第二级到倒数第二级如果出现空单元格,则退出j循环
- s = s & vbTab & arr(i, j)
- If InStr(d(s) & ",", "," & arr(i, j) & ",") = 0 Then d(s) = d(s) & "," & arr(i, j + 1) '字典条目是j+1级菜单
- Next
- ' If Len(arr(i, 2)) Then
- ' s = s & vbTab & arr(i, 2)
- ' If InStr(d(s) & ",", "," & arr(i, 3) & ",") = 0 Then d(s) = d(s) & "," & arr(i, 3) '字典条目是三级菜单
- ' If Len(arr(i, 3)) Then
- ' s = s & vbTab & arr(i, 3)
- ' If InStr(d(s) & ",", "," & arr(i, 4) & ",") = 0 Then d(s) = d(s) & "," & arr(i, 4) '字典条目是四级菜单
- ' End If
- ' End If
- Next
- k = Filter(d.Keys, vbTab, False) '一级分类,不含vbTab
- On Error Resume Next
- Application.CommandBars("树型菜单").Delete '删除可能存在的"树型菜单"菜单
- With Application.CommandBars.Add("树型菜单", msoBarPopup)
- For i = 0 To UBound(k)
- t2 = d(k(i)) '二级分类,每个二级分类用逗号隔开
- a2 = Split(t2, ",") '二级分类数组
- With .Controls.Add(Type:=IIf(Len(t2) > UBound(a2), msoControlPopup, msoControlButton)) '二级分类t2都是逗号,即没有实际项目,则msoControlButton
- .Caption = k(i)
- .OnAction = IIf(Len(t2) > UBound(a2), "", "'显示在活动单元格 """ & .Caption & """'")
- .BeginGroup = True '分组显示
- For j = 1 To UBound(a2) '逐个二级分类
- If Len(a2(j)) Then '如果二级分类不为空
- t3 = d(k(i) & vbTab & a2(j)) '三级分类,每个三级分类用逗号隔开
- a3 = Split(t3, ",") '三级分类数组
- With .Controls.Add(Type:=IIf(Len(t3) > UBound(a3), msoControlPopup, msoControlButton))
- .Caption = a2(j)
- .OnAction = IIf(Len(t3) > UBound(a3), "", "'显示在活动单元格 """ & .Caption & """'")
- For l = 1 To UBound(a3)
- If Len(a3(l)) Then
- t4 = d(k(i) & vbTab & a2(j) & vbTab & a3(l)) '四级分类,每个四级分类用逗号隔开
- a4 = Split(t4, ",") '四级分类数组
- With .Controls.Add(Type:=IIf(Len(t4) > UBound(a4), msoControlPopup, msoControlButton))
- .Caption = a3(l)
- .OnAction = IIf(Len(t4) > UBound(a4), "", "'显示在活动单元格 """ & .Caption & """'")
- For v = 1 To UBound(a4)
- If Len(a4(v)) Then
- With .Controls.Add(Type:=msoControlButton) '创建四级菜单
- .Caption = a4(v)
- .OnAction = "'显示在活动单元格 """ & a3(l) & Chr(10) & .Caption & """'" '四级菜单显示出三级和四级单元格内的内容,用行号符隔开
- End With
- End If
- Next
- End With
- End If
- Next
- End With
- End If
- Next
- End With
- Next
- End With
- End Sub
复制代码 |
|