从特定工作表子调用用户表单

另一个新手问题,但我无法find我的答案到目前为止…

我有一个工作簿几张,让我们打电话给他们S1,S2等,我有一个用户表单,可以从任何工作表激活的操作。

我在这里的问题是,我有参数从子传递给用户表单

Public c As Integer, lf As Integer, ld As Integer Sub Tri() ld = 8 lf = 128 Application.ScreenUpdating = False UsForm.Show End Sub 

现在我的工作手册正在不断增加,从S1到S2等不同,需要我根据启动的工作表来更改参数。 所以我从“模块”中删除我的代码,并将其放在“Microsoft Excel对象”部分。 但现在看来,它没有访问我的公共variables,只要我请求ld或lf,它显示为空(即使它在以前的用户窗体中实现)。

请有人能告诉我我错过了什么吗? 否则我该怎么办(我不想把数据放在表单里)?

您需要充分利用用户窗体是一个类的事实。 所以作为一个例子,将下面的代码添加到“表单”中。 假设您有一个名称为CommandButton1的button

 Option Explicit Dim mVar1 As Long Dim mVar2 As String Property Let Var1(nVal As Long) mVar1 = nVal End Property Property Let Var2(nVal As String) mVar2 = nVal End Property Private Sub CommandButton1_Click() MsgBox mVar1 & " - " & mVar2 Me.Hide End Sub 

然后你可以添加一个正常的模块

 Sub TestForm() Dim frm As UserForm1 Set frm = New UserForm1 Load frm frm.Var1 = 42 frm.Var2 = "Test" frm.Show Unload frm End Sub 

通过这种方式,您可以将variables传递给表单而不使用全局variables。

这是一个被广泛接受的关于variables范围的答案。 https://stackoverflow.com/a/3815797/3961708

如果你在这个工作簿里面放了你的variables,你需要通过完全限定它来访问它。 像ThisWorkbook.VariableName

但是对于用户表单,我build议使用数据stream属性。 这是干净而强大的方式来做到这一点。 习惯使用属性,你会发现它对UserForms非常有利。

例:

ThisWorkbook添加此代码

 Option Explicit '/ As this variable is defined in ThisWorkBook, you need to qualify it to access anywher else. '/ Example ThisWorkbook.x Public x As Integer Sub test() Dim uf As New UserForm1 x = 10 '/ Set the propertyvalue uf.TestSquare = 5 '/Show the form uf.Show '/ Get the property value MsgBox "Square is (by property) : " & uf.TestSquare '/Get Variable MsgBox "Square is (by variable) : " & x Unload uf End Sub 

现在添加一个UserForm,称为UserForm1并添加此代码

 Option Explicit Private m_lTestSquare As Long Public Property Get TestSquare() As Long TestSquare = m_lTestSquare End Property Public Property Let TestSquare(ByVal lNewValue As Long) m_lTestSquare = lNewValue End Property Private Sub UserForm_Click() '/ Accessing the Variable Defined inside ThisWorkkbook ThisWorkbook.x = ThisWorkbook.x * ThisWorkbook.x '/ Changing Property Value Me.TestSquare = Me.TestSquare * Me.TestSquare Me.Hide End Sub 

现在,当您从ThisWorkbook运行Test子时,您将看到如何在代码中访问variables和属性。