Гость
Целевая тема:
Создать новую тему:
Автор:
Форумы / Microsoft Office [игнор отключен] [закрыт для гостей] / (VBA Excel) Изменить пункт меню в CommandBar. / 11 сообщений из 11, страница 1 из 1
31.05.2006, 09:55:40
    #33762336
Аленочка
Участник
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
(VBA Excel) Изменить пункт меню в CommandBar.
Здравствуйте. У меня следующий вопрос:

Как при нажатии пункта меню 'Автоформат' изменить свойства данного Item'са?
А именно назначить другой макрос (например Макрос1) и сменить Caption на 'Отменить автоформат'.

Далее при нажатии на 'Отменить автоформат' выполнять вышеназначенный макрос (Макрос1) и опять менять Item'c, возвращая его обратно в исходное состояние (то есть старый макрос .OnAction = "AutoFormat" и Caption = "Автоформат").

Код: plaintext
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.
33.
34.
35.
36.
37.
38.
39.
40.
41.
42.
43.
Sub CreateCommandBar()
    Dim cb As CommandBar
    Dim cbButton As CommandBarPopup
    Dim newItem As CommandBarButton
    Dim newPopupItem As CommandBarPopup
    
    Set cb = Application.CommandBars.Add( _
      name:=cbName, _
      Position:=msoBarTop, _
      MenuBar:=False, _
      Temporary:=True)
    
    Set cbButton = cb.Controls.Add( _
      Type:=msoControlPopup, _
      Temporary:=True)

With cbButton
        .Caption = "&Настройки расчёта"
        .Tag = "Button2"
End With

Set newPopupItem = cbButton.Controls.Add(Type:=msoControlPopup)
With newPopupItem
    .BeginGroup = True
    .Caption = "Сводная таблица"
   End With
'-------------------------
Set newItem = newPopupItem.Controls.Add(Type:=msoControlButton)
With newItem
    .BeginGroup = True
    .Caption = "Автоформат"
    .FaceId =  542 
    .OnAction = "AutoFormat"
    .Style = msoButtonIconAndCaption
End With
'
-------------------------
cb.Visible = True
Set newItem = Nothing
Set cbButton = Nothing
Set cb = Nothing
Set newPopupItem = Nothing

End Sub
Аленочка тм
...
Рейтинг: 0 / 0
31.05.2006, 10:38:09
    #33762487
Ashton
Гость
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
(VBA Excel) Изменить пункт меню в CommandBar.
Могу предложить 2 варианта решения.

1-ый. Использовать свойство ActionControl в макросах.

Код: plaintext
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.
33.
34.
35.
36.
37.
38.
39.
40.
41.
42.
43.
44.
45.
46.
47.
48.
49.
50.
51.
52.
53.
54.
55.
56.
57.
58.
59.
60.
61.
62.
63.
64.
Public Sub CreateCommandBar()
    Dim cb As CommandBar
    Dim cbButton As CommandBarPopup
    Dim newItem As CommandBarButton
    Dim newPopupItem As CommandBarPopup
    
    Set cb = Application.CommandBars.Add( _
      Name:="Temp", _
      Position:=msoBarTop, _
      MenuBar:=False, _
      Temporary:=True)
    
    Set cbButton = cb.Controls.Add( _
      Type:=msoControlPopup, _
      Temporary:=True)

    With cbButton
        .Caption = "&Настройки расчёта"
        .Tag = "Button2"
    End With

    Set newPopupItem = cbButton.Controls.Add( _
      Type:=msoControlPopup)
    
    With newPopupItem
        .BeginGroup = True
        .Caption = "Сводная таблица"
    End With

    Set newItem = newPopupItem.Controls.Add( _
      Type:=msoControlButton)
    
    With newItem
        .BeginGroup = True
        .Caption = "Автоформат"
        .FaceId =  542 
        .OnAction = "AutoFormat"
        .Style = msoButtonIconAndCaption
    End With

    cb.Visible = True
    
    Set newItem = Nothing
    Set newPopupItem = Nothing
    Set cbButton = Nothing
    Set cb = Nothing
End Sub

Public Sub AutoFormat()
    MsgBox "Макрос AutoFormat"
    
    With Application.CommandBars.ActionControl
        .Caption = "Отменить автоформат"
        .OnAction = "Macro2"
    End With
End Sub

Public Sub Macro2()
    MsgBox "Макрос Macro2"

    With Application.CommandBars.ActionControl
       .Caption = "Автоформат"
        .OnAction = "AutoFormat"
    End With
End Sub

2-ый. Использовать событие Click кнопки.

Модуль класса Class1.

Код: plaintext
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
Public WithEvents newItem As Office.CommandBarButton

Private Sub newItem_Click( _
  ByVal Ctrl As CommandBarButton, _
  CancelDefault As Boolean)
    MsgBox "Click"
  
    If Ctrl.Caption = "Автоформат" Then
        Ctrl.Caption = "Отменить автоформат"
        Ctrl.OnAction = "Macro2"
    Else
        Ctrl.Caption = "Автоформат"
        Ctrl.OnAction = "AutoFormat"
    End If
End Sub

Стандартный модуль.

Код: plaintext
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.
33.
34.
35.
36.
37.
38.
39.
40.
41.
42.
43.
44.
45.
46.
47.
48.
49.
50.
51.
52.
53.
54.
55.
Dim cls As New Class1

Public Sub X()
    Dim cb As CommandBar
    Dim cbButton As CommandBarPopup
    Dim newItem As CommandBarButton
    Dim newPopupItem As CommandBarPopup
    
    Set cb = Application.CommandBars.Add( _
      Name:="Temp", _
      Position:=msoBarTop, _
      MenuBar:=False, _
      Temporary:=True)
    
    Set cbButton = cb.Controls.Add( _
      Type:=msoControlPopup, _
      Temporary:=True)

    With cbButton
        .Caption = "&Настройки расчёта"
        .Tag = "Button2"
    End With

    Set newPopupItem = cbButton.Controls.Add( _
      Type:=msoControlPopup)
    
    With newPopupItem
        .BeginGroup = True
        .Caption = "Сводная таблица"
    End With

    Set cls.newItem = newPopupItem.Controls.Add( _
      Type:=msoControlButton)
    
    With cls.newItem
        .BeginGroup = True
        .Caption = "Автоформат"
        .FaceId =  542 
        .OnAction = "AutoFormat"
        .Style = msoButtonIconAndCaption
    End With

    cb.Visible = True
    
    Set newPopupItem = Nothing
    Set cbButton = Nothing
    Set cb = Nothing
End Sub

Public Sub AutoFormat()
    MsgBox "Макрос AutoFormat"
End Sub

Public Sub Macro2()
    MsgBox "Макрос Macro2"
End Sub
...
Рейтинг: 0 / 0
31.05.2006, 11:21:46
    #33762693
Аленочка
Участник
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
(VBA Excel) Изменить пункт меню в CommandBar.
2 Ashton

Спасибо большое. Поробую оба варианта. О результатах обязательно напишу...


Аленочка тм
...
Рейтинг: 0 / 0
31.05.2006, 11:29:13
    #33762728
Аленочка
Участник
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
(VBA Excel) Изменить пункт меню в CommandBar.
первый вариант работает отлично...думаю: "стоит ли проверять второй ?";-)))
о свойстве ActionControl слышу впервые...это свойство помогает определить какая кнопка в менюшке была нажата последней?

Аленочка тм
...
Рейтинг: 0 / 0
31.05.2006, 12:04:24
    #33762899
Ashton
Гость
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
(VBA Excel) Изменить пункт меню в CommandBar.
ActionControl PropertyReturns the CommandBarControl object whose OnAction property is set to the running procedure. If the running procedure was not initiated by a command bar control, this property returns Nothing. Read-only.
...
Рейтинг: 0 / 0
01.06.2006, 03:43:58
    #33764835
Аленочка
Участник
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
(VBA Excel) Изменить пункт меню в CommandBar.
всё ясно. спасибо.

Аленочка тм
...
Рейтинг: 0 / 0
01.06.2006, 06:12:42
    #33764860
Аленочка
Участник
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
(VBA Excel) Изменить пункт меню в CommandBar.
Требуется небольшая доработка сабжа.

Нужно чтобы при нажатии кнопки "Сформировать" также изменялись свойства кнопки, которая отвечает за автоформатирование ("Автоформат" либо "Отменить автоформат").

Необходимо сделать так, чтобы при нажатии на "Сформировать", если кнопка с Caption'ом "Автоформат" отсутствует в меню, искать кнопку с Caption'ом "Отменить автоформат" и менять её параметры, а имено поменять Caption на "Автоформат" и OnAction на "AutoFormat".

Вот такая вот задачка. Подскажите как искать кнопку в менюшке по заданному Caption и изменять её свойства.

Менюшка та же самая:

Код: plaintext
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.
33.
34.
35.
36.
37.
38.
39.
40.
41.
42.
43.
Sub CreateCommandBar()
    Dim cb As CommandBar
    Dim cbButton As CommandBarPopup
    Dim newItem As CommandBarButton
    Dim newPopupItem As CommandBarPopup
    
    Set cb = Application.CommandBars.Add( _
      name:=cbName, _
      Position:=msoBarTop, _
      MenuBar:=False, _
      Temporary:=True)
    
    Set cbButton = cb.Controls.Add( _
      Type:=msoControlPopup, _
      Temporary:=True)

With cbButton
        .Caption = "&Настройки расчёта"
        .Tag = "Button2"
End With

Set newPopupItem = cbButton.Controls.Add(Type:=msoControlPopup)
With newPopupItem
    .BeginGroup = True
    .Caption = "Сводная таблица"
   End With
'-------------------------
Set newItem = newPopupItem.Controls.Add(Type:=msoControlButton)
With newItem
    .BeginGroup = True
    .Caption = "Автоформат"
    .FaceId =  542 
    .OnAction = "AutoFormat"
    .Style = msoButtonIconAndCaption
End With
'
-------------------------
cb.Visible = True
Set newItem = Nothing
Set cbButton = Nothing
Set cb = Nothing
Set newPopupItem = Nothing

End Sub

Аленочка тм
...
Рейтинг: 0 / 0
01.06.2006, 08:50:10
    #33764961
Ashton
Гость
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
(VBA Excel) Изменить пункт меню в CommandBar.
Аленочка, что-то я не вижу в твоем коде кнопку "Сформировать".

Шаг 1. Создаем панель.

Код: plaintext
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.
33.
34.
35.
36.
37.
38.
39.
40.
41.
42.
43.
44.
45.
46.
47.
Public Sub CreateCommandBar()
    Dim cb As CommandBar
    Dim cbButton As CommandBarPopup
    Dim newItem As CommandBarButton
    Dim newPopupItem As CommandBarPopup
    
    Set cb = Application.CommandBars.Add( _
      Name:="Temp", _
      Position:=msoBarTop, _
      MenuBar:=False, _
      Temporary:=True)
    
    Set cbButton = cb.Controls.Add( _
      Type:=msoControlPopup, _
      Temporary:=True)

    With cbButton
        .Caption = "&Настройки расчёта"
        .Tag = "Button2"
    End With

    Set newPopupItem = cbButton.Controls.Add( _
      Type:=msoControlPopup)
    
    With newPopupItem
        .BeginGroup = True
        .Caption = "Сводная таблица"
    End With

    Set newItem = newPopupItem.Controls.Add( _
      Type:=msoControlButton)
    
    With newItem
        .BeginGroup = True
        .Caption = "Автоформат"
        .FaceId =  542 
        .OnAction = "AutoFormat"
        .Style = msoButtonIconAndCaption
        .Tag = "Автоформат"
    End With

    cb.Visible = True
    
    Set newItem = Nothing
    Set newPopupItem = Nothing
    Set cbButton = Nothing
    Set cb = Nothing
End Sub

Шаг 2. Кнопка "Сформировать", расположенная на листе.

Код: plaintext
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
Private Sub CommandButton1_Click()
    Dim ctl As CommandBarControl
         
    Set ctl = CommandBars.FindControl( _
     Type:=msoControlButton, _
     Tag:="Автоформат")
    
    If Not ctl Is Nothing Then
        If ctl.Caption = "Автоформат" Then
            ctl.Caption = "Отменить автоформат"
            ctl.OnAction = "Macro2"
        Else
            ctl.Caption = "Автоформат"
            ctl.OnAction = "AutoFormat"
        End If
    End If
End Sub
...
Рейтинг: 0 / 0
01.06.2006, 09:11:02
    #33764986
Аленочка
Участник
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
(VBA Excel) Изменить пункт меню в CommandBar.
Извините, кнопки "Сформировать" действительно не было в предыдущем посте. Потому что я, чтобы не приводить полностью, немного обрезала код и благополучно про это забыла.

У меня получилось вот так:
(в принципе тоже ничего сложного)

Код: plaintext
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
Sub MenuTest()

Dim a As CommandBarPopup
Dim b As CommandBarPopup
Dim c As CommandBarButton

Set a = CommandBars("Custom CommandBar").Controls( 2 )
Set b = a.Controls( 2 )
Set c = b.Controls( 2 )

With c
    If .Type = msoControlButton Then
        If .Caption = "Отменить автоформат" Then
            .Caption = "Автоформат"
            .OnAction = "AutoFormat"
        End If
    End If
End With

Set a = Nothing
Set b = Nothing
Set c = Nothing

End Sub

А вам, Ashton, также спасибо огромное за ответы.
Про FindControl - тоже хотела им воспользоваться. Приберегу на следующий раз

Аленочка тм
...
Рейтинг: 0 / 0
01.06.2006, 09:16:16
    #33764993
Аленочка
Участник
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
(VBA Excel) Изменить пункт меню в CommandBar.
В этом куске кода:

Код: plaintext
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
Private Sub CommandButton1_Click()
    Dim ctl As CommandBarControl
         
    Set ctl = CommandBars.FindControl( _
     Type:=msoControlButton, _
     Tag:="Автоформат")
    
    If Not ctl Is Nothing Then
        If ctl.Caption = "Автоформат" Then
            ctl.Caption = "Отменить автоформат"
            ctl.OnAction = "Macro2"
        Else
            ctl.Caption = "Автоформат"
            ctl.OnAction = "AutoFormat"
        End If
    End If
End Sub

Лучше наверное сократить вот так, потому что если пункта "Отменить автоформат" нет, то и менять ничего не нужно:

Код: plaintext
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
Private Sub CommandButton1_Click()
    Dim ctl As CommandBarControl
         
    Set ctl = CommandBars.FindControl( _
     Type:=msoControlButton, _
     Tag:="Отменить автоформат")
    
    If Not ctl Is Nothing Then
        If ctl.Caption = "Отменить автоформат" Then
            ctl.Caption = "Автоформат"
            ctl.OnAction = "AutoFormat"
        End If
End Sub

set ctl = Nothing
Аленочка тм
...
Рейтинг: 0 / 0
01.06.2006, 09:36:29
    #33765035
Ashton
Гость
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
(VBA Excel) Изменить пункт меню в CommandBar.
В параметре Tag метода FindControl мы указываем название, которое указали при формировании кнопки, а не само название кнопки.

Код: plaintext
1.
2.
3.
4.
5.
6.
7.
8.
9.
    ...
    With newItem
        .BeginGroup = True
        .Caption = "Автоформат"
        .FaceId =  542 
        .OnAction = "AutoFormat"
        .Style = msoButtonIconAndCaption
        .Tag = "Button3" ' <---
    End With
    ...

Код: plaintext
1.
2.
    Set ctl = CommandBars.FindControl( _
     Type:=msoControlButton, _
     Tag:="Button3") ' <---
...
Рейтинг: 0 / 0
Форумы / Microsoft Office [игнор отключен] [закрыт для гостей] / (VBA Excel) Изменить пункт меню в CommandBar. / 11 сообщений из 11, страница 1 из 1
Найденые пользователи ...
Разблокировать пользователей ...
Читали форум (0):
Пользователи онлайн (0):
x
x
Закрыть


Просмотр
0 / 0
Close
Debug Console [Select Text]