在用户窗体之间传递数据

Pass data between UserForms

在 Excel VBA 我有一个类似于下面的用户表单,用户在其中输入 ID 号,然后详细信息显示在用户表单上:

Private Sub btnIDNo_Click()
Dim IDNo As Long
If txtIDNo.Text <> "" Then
    If IsNumeric(txtIDNo.Text) = True Then
        lblError.Caption = ""
        IDNo = txtIDNo.Text
        Worksheets("Details").Activate
        Range("B4").Select
        While ActiveCell.Value <> "" And ActiveCell.Value <> IDNo
            ActiveCell.Offset(1, 0).Select
        Wend
        If ActiveCell.Value = IDNo Then
            txtName.Value = ActiveCell.Offset(0, 1).Value
            txtPhone.Value = ActiveCell.Offset(0, 2).Value
        Else
            lblError.Caption = "Cannot find ID nummber"
        End If
    Else
        lblError.Caption = "Please enter the ID Number in numeric form"
    End If
End If
End Sub

在详细信息用户表单上,我有一个 "Edit" 按钮。单击 "Edit" 按钮将打开另一个用户表单,用户可以在其中更改该 ID 号的详细信息,但显然不能更改 ID 号本身。为此,我需要将 ID 号从 Details User Form 传递到 Edit User Form。有办法吗?

显示详细信息用户表单底部打开编辑用户表单类似于以下内容:

Private Sub CommandButton1_Click()
Dim IDNo As Long
If txtIDNo.Text <> "" Then
    If IsNumeric(txtIDNo.Text) = True Then
        lblError.Caption = ""
        IDNo= txtIDNo.Text
        ufmEditDetails.Show
        ufmShowDetails.Hide
    Else
        lblError.Caption = "Please enter the ID Number in numeric form"
    End If
Range("B4").Select
End If
End Sub

我已经查看了以下链接,但它们似乎没有帮助:

http://www.mrexcel.com/forum/excel-questions/671964-visual-basic-applications-pass-variables-between-user-forms.html

http://gregmaxey.mvps.org/word_tip_pages/userform_pass_data.html

http://peltiertech.com/Excel/PropertyProcedures.html

有几种方法可以解决这个问题。 我使用的是在模块

中声明全局变量或 public 变量

示例:

Public commonVariable As String

然后在用户窗体中,您可以从该变量中分配或检索值。 例如 在用户表单 1 中:

Private Sub btnIDNo_Click()
    commonVariable = "UserId"
End Sub

在用户窗体 2 中:

Private Sub CommandButton1_Click()
    me.txtIDNo.Text = commonVariable 
End Sub

有很多方法...这里有一些...

方式一

  1. 在模块中声明一个 Public 变量
  2. 在 Userform1 中分配给该变量,然后启动 Userform2。该变量将保留其值。范例

在用户表单 1 中

Private Sub CommandButton1_Click()
    MyVal = "Sid"
    UserForm2.Show
End Sub

在 Userform2 中

Private Sub CommandButton1_Click()
    MsgBox MyVal
End Sub

在模块中

Public MyVal

方式 2

使用用户表单.Tag 属性

在用户表单 1 中

Private Sub CommandButton1_Click()
    UserForm2.Tag = "Sid"
    UserForm2.Show
End Sub

在 Userform2 中

Private Sub CommandButton1_Click()
    MsgBox Me.Tag
End Sub

方式三

在Userform2中添加一个Label并将其可见属性设置为False

在用户表单 1 中

Private Sub CommandButton1_Click()
    UserForm2.Label1.Caption = "Sid"
    UserForm2.Show
End Sub

在 Userform2 中

Private Sub CommandButton1_Click()
    MsgBox Label1.Caption
End Sub

最简单的方法是:

UserForm2.TxtIDNo.Text = UserForm1.txtIDNo.Text