我怎样才能运行从宏观用户窗体?

问题描述 投票:1回答:2

我开发了很多的UDF和宏VBA为Excel 2016年我的一个宏使用一个输入框来获得由宏随后使用数据。我想用一个用户表单更换输入框。我创建了用户的形式,用一个文本框。我想激活用户表单,默认数据填充文本框,并选择确定,当文本框中数据返回给宏。我已经广泛地搜索了一个终端到终端例如对所有为此所需的代码,没有运气。确实存在这个简单的问题的例子吗?

excel vba userform
2个回答
0
投票

属性添加到您的用户窗体。对于这个答案,让我们用用户表单中的以下代码。

Public Property Get MyResult() As String
    ' You may want to do any manipulation here
    ' including converting to a number, in which case the return type should be changed (*)
    MyResult = TextBox1.Text
End Property

(*)如果你正在做的转换,你可以有另一种功能,用户表单中,直到他们在文本框中有效转换数据禁用“确定”按钮。

你也想知道,如果他们点击“取消”

Public Property Get Cancelled() As Boolean
    Cancelled = pCancelled ' Declare pCancelled as a Boolean in the scope of the form
End Property

Public Sub CancelButton_Click() ' Standard click event for the button
    pCancelled = True
    Me.Hide
End Sub

Public Sub OKButton_Click() ' Standard click event for the button
    pCancelled = False
    Me.Hide
End Sub

在你调用宏

MyForm.Show ' This is modal, so will block execution until a response is provided
If Not MyForm.Cancelled Then
    Debug.Print MyForm.MyResult
    'Do something with MyForm.MyResult
End If
UnLoad MyForm ' assuming you do not want to re-use this form as part of your logic.

0
投票

还有就是你怎么能值传递给表单并得到结果回来的例子。该方法使用标准模块范围内创建并传递给用户窗体,以允许值要被改变Scripting.Dictionary对象。因此,它使能够在字典中发送默认值用户窗体,并保持结果值甚至在用户窗体关闭和卸载。您可能有多个值,只需添加键的必要量的字典,如G。 oData("property1")oData("property2")等。

添加一个标准模块项目,并把下面的代码到其中:

Option Explicit

Sub Test()

    Dim oData

    ' Set default value and show form
    Set oData = CreateObject("Scripting.Dictionary")
    oData("") = "Some default text"
    UserForm1.ShowForm oData
    ' Wait until user close form
    Do While IsUserFormLoaded("UserForm1")
        DoEvents
    Loop
    ' Output returned value
    MsgBox oData("")

End Sub

Function IsUserFormLoaded(UserFormName As String) As Boolean

    Dim oUF As Object

    For Each oUF In UserForms
        If LCase(oUF.Name) = LCase(UserFormName) Then
            IsUserFormLoaded = True
            Exit Function
        End If
    Next

End Function

添加一个名为UserForm1到项目中的用户窗体模块,如图所示的地方控制:

userform

并把下面的代码插入到用户窗体模块:

Private opData

Public Sub ShowForm(oData)

    Set opData = oData
    Me.TextBox1.Value = opData("")
    Me.Show

End Sub

Private Sub UserForm_Initialize()

    If TypeName(opData) <> "Dictionary" Then Set opData = CreateObject("Scripting.Dictionary")

End Sub

Private Sub CommandButton1_Click()

    Unload Me

End Sub

Private Sub CommandButton2_Click()

    opData("") = Me.TextBox1.Value
    Unload Me

End Sub
© www.soinside.com 2019 - 2024. All rights reserved.