有没有办法在模块间使用局部变量? [英] Is there a way to use local variables across modules?
问题描述
是否有必要全局声明这些变量?我不喜欢全局变量,因为它们在代码执行后留在内存中,我必须在宏的开头逐个重置这些变量。我不能使用关键字End来清除内存中的变量,因为我需要记住这些变量中的一个或者两个。人们通常如何做?
编辑:有没有办法将Userform的变量传递给模块而不创建全局变量?
在userform中创建一个公共属性,并使用该属性将该变量传递给该表单。 Useforms只是类模块,除了它们有一个用户界面组件。示例:在用户窗体的代码模块中
Option Explicit
私有msLocalVar As String
公共属性Get LocalVar()As String
LocalVar = msLocalVar
结束属性
公共属性让LocalVar(sLocalVar As String)
msLocalVar = sLocalVar
结束属性
Private Sub CommandButton1_Click()
Me.LocalVar = Me.LocalVar& more strings attached
Me.Hide
End Sub
在标准模块中
Sub ShowForm()
Dim sLocalVar As String
Dim ufUserForm1 As UserForm1
sLocalVar =Some string
设置ufUserForm1 = New UserForm1
ufUserForm1.LocalVar = sLocalVar'传入变量
ufUserForm1.Show
'执行后的.Hide形式
Debug.Print ufUserForm1.LocalVar
'关闭窗体 - 以前只是隐藏
卸载ufUserForm1
End Sub
I have a VBA project with a Module and a Userform. I want to use some variables from my module in my Userform.
Is it necessary that I declare these variables globally? I don't like global variables because they stay in memory after the code's execution, and I have to reset these variables one-by-one at the beginning of my macro. I can't use the keyword End to clear the variables from memory because I need to remember one or two of these variables. How do people usually do?
Edit: is there a way to pass a variable from the Userform to the module without creating a global variable?
Create a Public Property in your userform and pass the variable into the form using the property. Useforms are just class module except that they have a user interface component. Example: In your userform's code module
Option Explicit
Private msLocalVar As String
Public Property Get LocalVar() As String
LocalVar = msLocalVar
End Property
Public Property Let LocalVar(sLocalVar As String)
msLocalVar = sLocalVar
End Property
Private Sub CommandButton1_Click()
Me.LocalVar = Me.LocalVar & " more strings attached"
Me.Hide
End Sub
And in a standard module
Sub ShowForm()
Dim sLocalVar As String
Dim ufUserForm1 As UserForm1
sLocalVar = "Some string"
Set ufUserForm1 = New UserForm1
ufUserForm1.LocalVar = sLocalVar 'pass in variable
ufUserForm1.Show
'This executes after the .Hide in the form
Debug.Print ufUserForm1.LocalVar
'Close out the form - previously just hidden
Unload ufUserForm1
End Sub
这篇关于有没有办法在模块间使用局部变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!