在用户窗体之间传递数据

6

在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

在“用户详细信息”表单上,我有一个“编辑”按钮。点击“编辑”按钮会打开另一个用户表单,用户可以更改该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


您是否考虑将您目前的两个表单实现为一个带有多页控件的单一表单?您可以将当前在第一个表单上的字段放在多页的第一页上,将当前在第二个表单上的字段放在第二页上。您可以默认情况下使第二页不可见,并在单个表单中的代码中控制何时显示第二页。 - Mark Moore
3个回答

22

有许多种方法... 以下是其中一些...

方法1

  1. 在模块中声明一个 Public 变量
  2. 在 Userform1 中为该变量赋值,然后启动 Userform2。该变量将保留其值。示例:

在 Userform1 中:

Private Sub CommandButton1_Click()
    MyVal = "Sid"
    UserForm2.Show
End Sub
在Userform2中
Private Sub CommandButton1_Click()
    MsgBox MyVal
End Sub

在模块中

Public MyVal

方法二

使用用户窗体的.Tag属性

在Userform1中

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

在 Userform2 中

Private Sub CommandButton1_Click()
    MsgBox Me.Tag
End Sub

第三种方法

在 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

1
最简单的方法难道不是 UserForm2.Txtbox.Text = UserForm1.txtIDNo.Text 吗? - DragonSamu
1
是的,这样做没问题 :) 我回答了“如何在用户表单之间传递数据”的问题。就你的回答而言,我已经在方法3中演示了类似的概念 :) - Siddharth Rout

2

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

示例:

Public commonVariable As String

然后在用户窗体中,您可以分配或检索此变量的值。 例如,在UserForm1中:

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

在UserForm2中:

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

1
最简单的方法是:

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接