BrianZ
BrianZ

Reputation: 249

VBA How do you copy and paste in a Userform using right-click?

I want to allow users to be able to paste values into TextBoxes in a userForm in VBA. You can use Ctrl-v just fine, but not everyone knows how to do that.

How do I enable copy and pasting using a right-click menu?

Upvotes: 3

Views: 17260

Answers (2)

B Hart
B Hart

Reputation: 1118

I realize this is an old post but I believe there is a more efficient method.
Userform Contextual Menu class code

http://www.andypope.info/vba/uf_contextualmenu.htm

There are even sample excel spreadsheets for the code examples.

The class module handles the construction of the contextual menu, the capture of right clicking in textboxes and the actual Cut. Copy and Paste actions. The class makes use of the userform's ActiveControl object. The code even handles controls within container controls such as Frames and Multipage.

The follow Initialization code, from the userform, shows how simple it is to define and use the class object. You only need declare a variable to the object and then set a reference for each textbox you want to have contextual menu capabilities. You can loop through all controls and automatically reference each textbox.

Private m_colContextMenus As Collection

Private Sub UserForm_Initialize()

    Dim clsContextMenu As CTextBox_ContextMenu
    Dim cTRL as Control

    Set m_colContextMenus = New Collection

    For Each cTRL In Me.Controls
        Select Case TypeName(cTRL)
        Case "TextBox"
            'MsgBox cTRL.Name & ": " & Me.Controls(cTRL.Name).Value          
            Set clsContextMenu = New CTextBox_ContextMenu
            With clsContextMenu
                Set .TBox = Me.Controls(cTRL.Name)
                Set .Parent = Me
            End With
            m_colContextMenus.Add clsContextMenu, CStr(m_colContextMenus.Count + 1)
        Case Else
            'MsgBox TypeName(cTRL) & ": " & cTRL.Name
        End Select
    Next

End Sub

Download example workbook which contains both .xls and .xlsm files

Upvotes: 3

Fionnuala
Fionnuala

Reputation: 91336

This may be of interest: http://word.mvps.org/faqs/userforms/AddRightClickMenu.htm

Upvotes: 1

Related Questions