在excel里,用VBA添加菜单和子菜单的示例代码:
Sub 添加菜单()
On Error Resume Next
Application.CommandBars("人事管理主菜单").Delete
Dim 主菜单 As CommandBar
Dim 子菜单 As CommandBarControl
Set 主菜单 = Application.CommandBars.Add(temporary:=True)
Dim BER As CommandBarControl
With 主菜单
.Visible = True
.Name = "人事管理主菜单"
.Position = msoBarTop
'******************开始添加文件子菜单*********************
Set 子菜单 = 主菜单.Controls.Add(Type:=msoControlPopup)
子菜单.Caption = "文件(&F)"
With 子菜单
Set BER = .Controls.Add(Type:=msoControlButton)
With BER
.Caption = "保存"
.BeginGroup = True
.OnAction = "保存"
.FaceId = 3
End With
Set BER = .Controls.Add(Type:=msoControlButton)
With BER
.Caption = "打印预览 "
.BeginGroup = True
.OnAction = "打印预览"
.FaceId = 109
End With
Set BER = .Controls.Add(Type:=msoControlButton)
With BER
.Caption = "打印"
.FaceId = 4
.OnAction = "打印"
End With
Set BER = .Controls.Add(Type:=msoControlButton)
With BER
.Caption = "退出"
.BeginGroup = True
.OnAction = "退出"
.FaceId = 1640
End With
End With
'。。。。。。。。。。添加文件子菜单结束。。。。。。。。。。。
'******************开始添加员工信息子菜单*********************
Set 子菜单 = 主菜单.Controls.Add(Type:=msoControlPopup)
子菜单.Caption = "员工信息(&Y)"
With 子菜单
Set BER = .Controls.Add(Type:=msoControlButton)
With BER
.Caption = "员工信息基本操作"
.BeginGroup = True
.OnAction = "显示员工信息窗口"
.FaceId = 65
End With
Set BER = .Controls.Add(Type:=msoControlButton)
With BER
.Caption = "员工信息筛选"
.BeginGroup = True
.OnAction = "显示员工信息查询工作表"
.FaceId = 140
End With
End With
'。。。。。。。。。。添加员工信息子菜单结束。。。。。。。。。。。
'******************开始设置子菜单*********************
Set 子菜单 = 主菜单.Controls.Add(Type:=msoControlPopup)
子菜单.Caption = "设置(&S)"
With 子菜单
Set BER = .Controls.Add(Type:=msoControlButton)
With BER
.Caption = "添加基本信息"
.BeginGroup = True
.OnAction = "显示基础信息工作表"
.FaceId = 451
End With
Set BER = .Controls.Add(Type:=msoControlButton)
With BER
.Caption = "备份文件"
.BeginGroup = True
.OnAction = "文件备份"
.FaceId = 173
End With
Set BER = .Controls.Add(Type:=msoControlButton)
With BER
.Caption = "添加操作员"
.BeginGroup = True
.FaceId = 469
.OnAction = "添加操作员"
End With
End With
'。。。。。。。。。。添加设置子菜单结束。。。。。。。。。。。
End With
Set 主菜单 = Nothing
Set 子菜单 = Nothing
Set BER = Nothing
End Sub