Как добавить кнопки / текстовые поля с событиями в форму Excel - PullRequest
0 голосов
/ 13 июля 2020

Я пытаюсь программно сгенерировать форму справки, которая, помимо прочего, содержит список гиперссылок, по которым пользователь может щелкнуть, чтобы получить к ним доступ. Создание кнопок вручную невозможно, так как они подходят для многих, я оставил только 3 в этом примере (этот код создаст 3 кнопки, но только последняя имеет привязанное к нему событие, как я могу сгенерировать новые события для каждого новая кнопка?):


'form z_test - empty form with only code in the background

Option Explicit

Public tbPin As MSForms.textBox         ' The textbox control.
Dim objMyEventClass As New C_events       ' Create an object of the Class (where we declared the events).

Private Sub UserForm_Initialize()
    
    Dim arrHyperlinks, Hi, topI
    
    arrHyperlinks = Array("google.com", "bing.com", "facebook.com")
    topI = 30
    
    For Each Hi In arrHyperlinks
        Dim btEx As MSForms.CommandButton
        Set btEx = Me.Controls.add("Forms.CommandButton.1")
        With btEx
            .TOP = topI
            .Left = 10
            .Width = 130
            .Height = 25
            .Caption = Hi
        End With
        topI = topI + 30
        Set objMyEventClass.btEvents = btEx         ' Attach at event to the button.
    Next
End Sub

'class c_events
Option Explicit

Public WithEvents tbEvents As MSForms.textBox
Public WithEvents btEvents As MSForms.CommandButton

Private Sub btEvents_click()
   MsgBox btEvents.Caption
End Sub

С уважением, Даниил

1 Ответ

1 голос
/ 13 июля 2020

В вашем коде есть только один класс, который содержит 1 кнопку, и вы продолжаете накладывать кнопку внутри l oop. Таким образом, только последняя кнопка привязана к событию. Один из подходов к решению этой проблемы - иметь набор классов C_events. Вот ваш исходный код, слегка измененный для реализации этой идеи:

Option Explicit

Public tbPin As MSForms.TextBox         ' The textbox control.
Private ButtonEvents As Collection
Private objMyEventClass As C_events       ' Create an object of the Class (where we declared the events).

Private Sub UserForm_Initialize()
    
    Dim arrHyperlinks, Hi, topI
    
    arrHyperlinks = Array("google.com", "bing.com", "facebook.com")
    topI = 30
    Set ButtonEvents = New Collection
    
    For Each Hi In arrHyperlinks
        Set objMyEventClass = New C_events
        Dim btEx As MSForms.CommandButton
        Set btEx = Me.Controls.Add("Forms.CommandButton.1")
        With btEx
            .Top = topI
            .Left = 10
            .Width = 130
            .Height = 25
            .Caption = Hi
        End With
        topI = topI + 30
        Set objMyEventClass.btEvents = btEx         ' Attach at event to the button.
        ButtonEvents.Add objMyEventClass
    Next
End Sub
...