在用户窗体之间传递数据

在Excel VBA中,我有一个类似于下面的用户表单,用户input一个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 

在详细信息用户表单上,我有一个“编辑”button。 点击“编辑”button将打开另一个用户表单,用户可以在其中更改该ID号的详细信息,但显然不是ID号本身。 为此,我需要将“详细用户表单”中的ID号码传递给“编辑用户表单”。 有没有办法做到这一点?

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

 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

有很多种方法…这里有一些…

方法1

  1. 在模块中声明一个Publicvariables
  2. 在Userform1中分配给该variables,然后启动Userform2。 这个variables将保留它的值。 例

在Userform1中

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

在Userform2中

 Private Sub CommandButton1_Click() MsgBox MyVal End Sub 

在模块中

 Public MyVal 

方式2

使用用户.Tag属性

在Userform1中

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

在Userform2中

 Private Sub CommandButton1_Click() MsgBox Me.Tag End Sub 

方式3

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

在Userform1中

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

在Userform2中

 Private Sub CommandButton1_Click() MsgBox Label1.Caption End Sub 

有很多方法可以解决这个问题。 我使用的是在模块中声明全局或公共variables

例:

 Public commonVariable As String 

那么在用户表单中,您可以从这个variables中分配或检索值。 例如在userform1中:

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

在UserForm2中:

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

最简单的方法是:

UserForm2.TxtIDNo.Text = UserForm1.txtIDNo.Text