2017-01-05 65 views
1

另一个新手的问​​题,但我找不到我的答案至今一个窗体...呼叫从一个特定的片子

我有几张工作簿,让我们称之为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对象”部分。但它现在似乎没有权限访问我的公共变量,并且只要我请求ld或lf,它就显示为空(即使它在前面的用户窗体中实现)。

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

回答

1

您需要充分利用userform是一个类的事实。所以作为一个例子,将下面的代码添加到“表单”中。让我们假设你有一个按钮名为CommandButton1的

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 

添加在你可以传递变量的形式,而不使用全局变量的方式。

+0

这似乎是个窍门,我需要在我的工作簿中试用它。 你能不能很快提醒我,我不熟悉的让,得到,设置等属性? 谢谢(我会尽快验证我的工作簿) – PEagle

+0

正如所说的一个用户表单是一个类。一个很好的解释恕我直言,可以在这里找到http://excelmacromastery.com/vba-class-modules/,这里是属性的一章http://excelmacromastery.com/vba-class-modules/#Class_Module_Properties – Storax

+0

非常好,谢谢! – PEagle

1

这是一个被广泛接受的关于变量作用域的答案。 https://stackoverflow.com/a/3815797/3961708

如果您已在本工作簿中对您的变量进行了decalred,则需要通过完全限定它来访问它。像ThisWorkbook.VariableName

但与用户窗体我建议使用数据流属性。这是干净而强大的方式来做到这一点。习惯使用属性,你会发现它对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 

现在添加一个用户窗体,叫UserForm1,当您从ThisWorkbookTest子添加以下代码

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 

现在你会看到你如何在代码中访问变量和属性。

+0

对不起,我的工作让我远离文件。 我一步一步地运行代码并理解它的功能。 但是,对此工作簿部分内部违反的变量的访问返回错误:“找不到方法或数据成员” – PEagle

+0

非常感谢您对变量作用域的回答,我现在对此有更好的理解。 – PEagle