VBA 如何使用右键单击复制和粘贴用户表单?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2202498/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-11 11:18:38  来源:igfitidea点击:

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

vbacopy-pasteuserform

提问by BrianZ

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.

我希望允许用户能够将值粘贴到 VBA 中 userForm 中的 TextBoxes 中。您可以很好地使用 Ctrl-v,但并不是每个人都知道该怎么做。

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

如何使用右键单击菜单启用复制和粘贴?

回答by B Hart

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

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

There are even sample excel spreadsheets for the code examples.

甚至还有代码示例的示例 Excel 电子表格。

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.

类模块处理上下文菜单的构造、在文本框中右键单击和实际剪切的捕获。复制和粘贴操作。该类使用用户窗体的 ActiveControl 对象。该代码甚至可以处理容器控件中的控件,例如 Frames 和 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

下载包含 .xls 和 .xlsm 文件的示例工作簿