+ Reply to Thread
Results 1 to 13 of 13

Any way to avoid hardcoding control name inside the control event procedure?

Hybrid View

mc84excel Any way to avoid hardcoding... 03-04-2014, 08:16 PM
Richard Buttrey Re: Any way to avoid... 03-04-2014, 08:54 PM
mc84excel Re: Any way to avoid... 03-04-2014, 09:01 PM
Richard Buttrey Re: Any way to avoid... 03-04-2014, 09:06 PM
mc84excel Re: Any way to avoid... 03-04-2014, 09:47 PM
Norie Re: Any way to avoid... 03-04-2014, 09:09 PM
shg Re: Any way to avoid... 03-04-2014, 10:00 PM
mc84excel Re: Any way to avoid... 03-05-2014, 08:13 PM
Andy Pope Re: Any way to avoid... 03-05-2014, 04:55 AM
mc84excel Re: Any way to avoid... 03-05-2014, 07:53 PM
Kyle123 Re: Any way to avoid... 03-06-2014, 02:36 AM
mc84excel Re: Any way to avoid... 03-06-2014, 10:05 PM
mc84excel Re: Any way to avoid... 03-24-2015, 07:50 PM
  1. #1
    Valued Forum Contributor
    Join Date
    08-29-2012
    Location
    In lockdown
    MS-Off Ver
    Excel 2010 (2003 to 2016 but 2010 for choice)
    Posts
    1,766

    Cool Any way to avoid hardcoding control name inside the control event procedure?

    Just curious. Is there any way in VBA to refer to a control in its own event procedure without referring to it by name/hard-coding?

    It might be clearer to explain by a dummy code example:
    Private Sub CommandButton1_Click()
        With Me.Controls.Parent.Me.Child 'this would refer to CommandButton1 without hard-coding the control by name
            'do something with control
        End With
    End Sub
    (I'm seeking what I would need to replace Line1 with)
    Last edited by mc84excel; 03-04-2014 at 08:42 PM.
    *******************************************************

    HELP WANTED! (Links to Forum threads)
    Trying to create reusable code for Custom Events at Workbook (not Application) level

    *******************************************************

  2. #2
    Forum Moderator - RIP Richard Buttrey's Avatar
    Join Date
    01-14-2008
    Location
    Stockton Heath, Cheshire, UK
    MS-Off Ver
    Office 365, Excel for Windows 2010 & Excel for Mac
    Posts
    29,464

    Re: Any way to avoid hardcoding control name inside the control event procedure?

    What are you wanting to do with the control?
    Richard Buttrey

    RIP - d. 06/10/2022

    If any of the responses have helped then please consider rating them by clicking the small star icon below the post.

  3. #3
    Valued Forum Contributor
    Join Date
    08-29-2012
    Location
    In lockdown
    MS-Off Ver
    Excel 2010 (2003 to 2016 but 2010 for choice)
    Posts
    1,766

    Re: Any way to avoid hardcoding control name inside the control event procedure?

    Quote Originally Posted by Richard Buttrey View Post
    What are you wanting to do with the control?
    I want to reuse the same event procedure code for multiple controls on the same form. If I can have the control self reference itself, I can just copy/paste the same code into each controls procedure. Otherwise I will need to edit each copy to match that controls name.

  4. #4
    Forum Moderator - RIP Richard Buttrey's Avatar
    Join Date
    01-14-2008
    Location
    Stockton Heath, Cheshire, UK
    MS-Off Ver
    Office 365, Excel for Windows 2010 & Excel for Mac
    Posts
    29,464

    Re: Any way to avoid hardcoding control name inside the control event procedure?

    Hi,

    Yes I understand that, but then assuming you can self reference the control what are you wanting to happen? Are you trying to change the controls properties for instance?

  5. #5
    Valued Forum Contributor
    Join Date
    08-29-2012
    Location
    In lockdown
    MS-Off Ver
    Excel 2010 (2003 to 2016 but 2010 for choice)
    Posts
    1,766

    Re: Any way to avoid hardcoding control name inside the control event procedure?

    Quote Originally Posted by Richard Buttrey View Post
    Hi,

    Yes I understand that, but then assuming you can self reference the control what are you wanting to happen? Are you trying to change the controls properties for instance?
    No. I want all these controls to call the same procedure. The procedure will behave slightly different depending on which control called it.

    I was thinking of adding a string argument to the called procedure and in the controls procedure have something like below (dummy code):

    Private Sub CommandButton1_Click()
        With Me.Controls.Parent.Me.Child 'this would refer to CommandButton1 without hard-coding the control by name
            Call MySharedProcedureExample(.name)
        End With
    End Sub
    Of course I would still have to hard-code each controls name in the called procedure (in the Select Case section).

    Unless... What if I set a numbered tag to each control and then pass that as the argument? Or if I used RIGHT on the .Name to obtain a number and pass that? That would avoid hard-coding the control names in the called procedure.
    In any case, I'd still need the code to self reference the control (unless I want to edit each procedure after I copy the code - which I don't )


    I did look into using ActiveControl instead but that can't be used for Label controls (I need Labels as pseudo CommandButtons to create a toggled effect)
    Last edited by mc84excel; 03-04-2014 at 09:51 PM.

  6. #6
    Forum Guru Norie's Avatar
    Join Date
    02-02-2005
    Location
    Stirling, Scotland
    MS-Off Ver
    Microsoft Office 365
    Posts
    19,645

    Re: Any way to avoid hardcoding control name inside the control event procedure?

    Quote Originally Posted by mc84excel View Post
    I want to reuse the same event procedure code for multiple controls on the same form.
    You should be looking at using a class for that.
    If posting code please use code tags, see here.

  7. #7
    Forum Expert shg's Avatar
    Join Date
    06-20-2007
    Location
    The Great State of Texas
    MS-Off Ver
    2010, 2019
    Posts
    40,689

    Re: Any way to avoid hardcoding control name inside the control event procedure?

    Declare a collection with global scope. It will contain all of the controls handled by the same procedure.

    Create a class module to process the event of interest. Here's one for textboxes that must contain numeric strings for positive whole numbers:

    Option Explicit
    
    ' Constrains member textboxes to have non-negative whole number values only
    
    Public WithEvents clsTxtNum As MSForms.TextBox
    
    Public Property Set Control(txtNumNew As MSForms.TextBox)
        Set clsTxtNum = txtNumNew
    End Property
    
    Private Sub clsTxtNum_Change()
        Dim sVal        As String
        Dim bCodeChange As Boolean
    
        If bCodeChange Then Exit Sub
        If gbCodeChange Then Exit Sub
    
        sVal = clsTxtNum.Value
    
        If Len(sVal) = 0 Then GoTo Just0
        If Not IsNumeric(sVal) Then GoTo BadInp
        If Int(CDbl(sVal)) <> CDbl(sVal) Then GoTo BadInp
    
        wksQuo.Range(clsTxtNum.Name) = clsTxtNum.Value
        EnableControls
        SetLabels
    
    OuttaHere:
        bCodeChange = False
        Exit Sub
    
    BadInp:
        MsgBox Prompt:="Whole number numeric values only!", _
               Title:=gsTitle
    Just0:
        bCodeChange = True
        clsTxtNum.Value = "0"
        GoTo OuttaHere
    End Sub
    When the form initializes, create a class instance for each relevant textbox and add it to the collection.

                Select Case TypeName(ctl)
                    Case "CheckBox"
                        Set clsChk = New clsEventSinkChk
                        Set clsChk.Control = ctl
                        gcolCtl.Add Item:=clsChk
    
                    Case "OptionButton"
                        Set clsOpt = New clsEventSinkOpt
                        Set clsOpt.Control = ctl
                        gcolCtl.Add Item:=clsOpt
    
                    Case "TextBox"
                        If LCase(ctl.Name) Like "txtnum*" Then
                            Set clsTxtNum = New clsEventSinkTxtNum
                            Set clsTxtNum.Control = ctl
                            gcolCtl.Add Item:=clsTxtNum
                        Else
                            Set clsTxt = New clsEventSinkTxt
                            Set clsTxt.Control = ctl
                            gcolCtl.Add Item:=clsTxt
                        End If
    Entia non sunt multiplicanda sine necessitate

  8. #8
    Valued Forum Contributor
    Join Date
    08-29-2012
    Location
    In lockdown
    MS-Off Ver
    Excel 2010 (2003 to 2016 but 2010 for choice)
    Posts
    1,766

    Re: Any way to avoid hardcoding control name inside the control event procedure?

    Your code looks interesting shg. I will probably modify this to get a practical solution right now.

    For my theoretical knowledge, I'm still curious as to whether or not the VBA language allows a control to 'self-reference' itself without hard-coding the control name within the event procedure.

  9. #9
    Forum Guru Andy Pope's Avatar
    Join Date
    05-10-2004
    Location
    Essex, UK
    MS-Off Ver
    O365
    Posts
    20,482

    Re: Any way to avoid hardcoding control name inside the control event procedure?

    I need Labels as pseudo CommandButtons to create a toggled effect
    Why not use the toggle button control?

    As suggested the class approach is the way to go. Within the class you can obtain the controls name or tag or someother property in order to determine what code to execute.
    Cheers
    Andy
    www.andypope.info

  10. #10
    Valued Forum Contributor
    Join Date
    08-29-2012
    Location
    In lockdown
    MS-Off Ver
    Excel 2010 (2003 to 2016 but 2010 for choice)
    Posts
    1,766

    Re: Any way to avoid hardcoding control name inside the control event procedure?

    Quote Originally Posted by Andy Pope View Post
    Why not use the toggle button control?
    Slightly off topic for this thread - That wouldn't work for the form I'm designing - the pseudo label buttons have a picture (thanks for your help on that in another thread ) and act as "switches" between different sections of the form (by choosing different MultiPage and the style set to no tabs). So when a different section of the main form is chosen, that label goes sunken and disabled (all other pseudo buttons go raised and enabled) and then the multipage switches to the appropriate page. It's difficult to explain in words alone but I can assure you the end effect looks quite nice.

    Quote Originally Posted by Andy Pope View Post
    As suggested the class approach is the way to go. Within the class you can obtain the controls name or tag or someother property in order to determine what code to execute
    For a practical solution to this thread I may have to go down the class route (as recommended by yourself, shg & Norie). But I have theoretical curiosity as to whether the VBA language would allow you to create a 'self reference' to a control within that controls event procedure. The equivalent of Me!ControlName.

  11. #11
    Forum Guru Kyle123's Avatar
    Join Date
    03-10-2010
    Location
    Leeds
    MS-Off Ver
    365 Win 11
    Posts
    7,239

    Re: Any way to avoid hardcoding control name inside the control event procedure?

    No, it doesn't, you'd need to raise an event that passes in a reference to the object that has changed. As an example the worksheet change event passes in a reference to the range that has changed. The reason for this is simply that the event procedure isn't "the event" it is simply a sub that is run in response to the event being raised (so Me will always be the object from which the code is run - it has no concept of which control raised the event), the arguments are passed in byref so that when the sub finishes the code returns back to the code in the event raising object and this code can then work with the changed (or not) event arguments.

    To resolve your particular issue, it would be possible to take shg's code and pass a reference to the userform into it as well as a reference to the textbox. Create a public sub that takes as an argument a textbox object in the userform. Then simply call this from the created event handling class through the reference to the userform. You'd need to then be mindful of creating circular references and make sure that all your objects are disposed of properly.

    I have given you at least 1 example of this working in practice when you wanted to create a fancy dropdown box with controls in
    Last edited by Kyle123; 03-06-2014 at 02:45 AM.

  12. #12
    Valued Forum Contributor
    Join Date
    08-29-2012
    Location
    In lockdown
    MS-Off Ver
    Excel 2010 (2003 to 2016 but 2010 for choice)
    Posts
    1,766

    Re: Any way to avoid hardcoding control name inside the control event procedure?

    Quote Originally Posted by Kyle123 View Post
    No, it doesn't, you'd need to raise an event that passes in a reference to the object that has changed. As an example the worksheet change event passes in a reference to the range that has changed. The reason for this is simply that the event procedure isn't "the event" it is simply a sub that is run in response to the event being raised (so Me will always be the object from which the code is run - it has no concept of which control raised the event), the arguments are passed in byref so that when the sub finishes the code returns back to the code in the event raising object and this code can then work with the changed (or not) event arguments.
    Pity. It would have been handy.

    Quote Originally Posted by Kyle123 View Post
    To resolve your particular issue, it would be possible to take shg's code and pass a reference to the userform into it as well as a reference to the textbox. Create a public sub that takes as an argument a textbox object in the userform. Then simply call this from the created event handling class through the reference to the userform. You'd need to then be mindful of creating circular references and make sure that all your objects are disposed of properly. I have given you at least 1 example of this working in practice when you wanted to create a fancy dropdown box with controls in
    I hadn't forgotten that you did that (That code proved to be very useful in that project)
    In fact, I had been thinking there would be less for me to modify in your code as opposed to the code provided by shg (no offence intended to shg)

  13. #13
    Valued Forum Contributor
    Join Date
    08-29-2012
    Location
    In lockdown
    MS-Off Ver
    Excel 2010 (2003 to 2016 but 2010 for choice)
    Posts
    1,766

    Re: Any way to avoid hardcoding control name inside the control event procedure?

    And it's solved. I've worked out a way whereby every command button can be set up to call another sub on the same form without needing to hardcode the button name in the call

    e.g.
    Private Sub CommandButton1_Click()
        Call ThisFormsCommandButtonRedirect
    End Sub
    instead of
    Private Sub CommandButton1_Click()
        Call ThisFormsCommandButtonRedirect(CommandButton1) 'note that argument would require either the control or the controls name
    End Sub

    Find the solution at http://www.excelforum.com/excel-prog...t-clicked.html
    Last edited by mc84excel; 03-24-2015 at 07:54 PM.

+ Reply to Thread

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Similar Threads

  1. [SOLVED] show jpeg picture inside a userform image control box
    By cfinch100 in forum Excel Programming / VBA / Macros
    Replies: 31
    Last Post: 07-29-2013, 03:44 PM
  2. [SOLVED] Userform multipage control - exit event not firing or event order
    By jane serky in forum Excel Programming / VBA / Macros
    Replies: 2
    Last Post: 06-14-2013, 10:23 AM
  3. Macro does not function inside a list control
    By Stephen Giles in forum Excel Programming / VBA / Macros
    Replies: 0
    Last Post: 08-08-2006, 03:40 PM
  4. [SOLVED] Send a frame control to a procedure as a parameter
    By JDMils in forum Excel Programming / VBA / Macros
    Replies: 1
    Last Post: 06-03-2006, 08:15 AM
  5. Avoid Control Cell changing.
    By Adeptus - ExcelForums.com in forum Excel Programming / VBA / Macros
    Replies: 1
    Last Post: 08-10-2005, 09:05 AM

Tags for this Thread

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts

Search Engine Friendly URLs by vBSEO 3.6.0 RC 1