下面的代码中 with 用得太多,该如何简化?
Sub 自制菜单()
With CommandBars("自制菜单").Controls(3).Controls.Add(, , , 11, True)
.Caption = "添加(&T)"
.OnAction = "增加"
With CommandBars("自制菜单").Controls(3).Controls.Add(, , , 12, True)
.Caption = "恢复(&H)"
.OnAction = "恢复"
With CommandBars("自制菜单").Controls(3).Controls.Add(, 271, , 13, True)
.Caption = "保存(&S)"
.OnAction = "保存"
With CommandBars("自制菜单").Controls(4).Controls.Add(, , , 1, True)
.Caption = "帮助(&H)"
.OnAction = "说明"
With CommandBars("自制菜单").Controls(4).Controls.Add(, , , 2, True)
.Caption = "演示"
.OnAction = "演示"
End With
End With
End With
End With
End With
End Sub
解答:
With .Controls(3).Controls
Set c = .Add(, , , 11, True)
c.Caption = "添加(&T)"
c.OnAction = "增加"
Set c = .Add(, , , 12, True)
c.Caption = "恢复(&H)"
c.OnAction = "恢复"
Set c = .Add(, 271, , 13, True)
c.Caption = "保存(&S)"
c.OnAction = "保存"
End With
With .Controls(4).Controls
Set c = .Add(, , , 1, True)
c.Caption = "帮助(&H)"
c.OnAction = "说明"
Set c = .Add(, , , 2, True)
c.Caption = "演示"
c.OnAction = "演示"
End With
End With
用 With 就是要把相同的对象集中一次写,为的是简化代码也减少错误