Excel 为什么VBA不允许我在userform中的commandbutton中声明公共数组?
我的任务: 我有一个用户表单,上面有各种复选框。用户应选中/取消选中这些框,并在完成后按“完成”按钮。按“Done”应该启动一个数组,并根据代码用字符串值填充它。到目前为止,一切顺利 我的问题是: 但是,因为我需要另一个模块中的数组,所以它必须是公共的。我已将其公开,如下面我的代码中所示。然而,这是错误的。我做错了什么 谢谢Excel 为什么VBA不允许我在userform中的commandbutton中声明公共数组?,excel,vba,Excel,Vba,我的任务: 我有一个用户表单,上面有各种复选框。用户应选中/取消选中这些框,并在完成后按“完成”按钮。按“Done”应该启动一个数组,并根据代码用字符串值填充它。到目前为止,一切顺利 我的问题是: 但是,因为我需要另一个模块中的数组,所以它必须是公共的。我已将其公开,如下面我的代码中所示。然而,这是错误的。我做错了什么 谢谢 Option Base 1 Public dimArray(5, 4) As String Private Sub cmdBtn_Done_Click() Unload
Option Base 1
Public dimArray(5, 4) As String
Private Sub cmdBtn_Done_Click()
Unload ProductDimension
'1st Dimension
If chk_AbilityOfInteraction = True Then
dimArray(1, 1) = "Functionality"
dimArray(1, 2) = "Ability of interaction"
End If
If chk_Performance = True Then
dimArray(1, 1) = "Functionality"
dimArray(1, 3) = "Performance"
End If
....
End Sub
由于您希望在另一个模块中获得用户表单的结果,因此可以在标准代码模块中使用下面的代码。它是一个返回所需数组的函数。那么,在这个过程中,你需要你应该拥有的数组吗
Dim Arr() As String
Arr = GetArray
下面是函数GetArray:-
Function GetArray() As String()
' "UserForm1" must be the name you gave to the UserForm.
' It's "UserForm1" by default but you did well if you changed the name.
Dim MyForm As UserForm1
Dim Arr(1 To 3) As String
Set MyForm = New UserForm1 ' this is the actual form's name, too
With MyForm
' although the form isn't visible, you can
' set or modify any of its controls:-
.chk_AbilityOfInteraction.Value = False
.Show ' now MyForm takes over control
' until "Hide" is encountered in
' the form's own code.
' Your "Done" button should trigger
' this action.
' upon "Me.Hide" the code resumes here
' The form is only hidden. All it's controls are still in memory.
Arr(1) = "Functionality"
If .chk_AbilityOfInteraction.Value = True Then
Arr(2) = "Ability of Interaction"
Else
Arr(3) = "Performance"
End If
End With
Unload MyForm ' now the form is killed
' if not killed you might "Show" it again
' with all previous values still in it.
Set MyForm = Nothing
GetArray = Arr ' this sets the function's return value
End Function
读一读,然后读链接的博客文章。一个
UserForm
是一个类(不是模块),所以你应该把它当作一个类来对待。非常感谢,这看起来很有希望!我现在读一遍。很抱歉有一个可能很琐碎的帖子,我才刚开始…非常感谢您的详细回答!您在代码中提到的一个关键元素是“Hide”,这是我以前不知道的。尽管您的解决方案是完美的,但这实际上帮助我找到了一个不同的、简单的解决方案:我包含了将数组填充到普通模块而不是用户表单中的代码。在“卸载”userform之前,这不起作用,因为此时复选框中的数据已被删除。使用“.Hide”可以很好地填充数组!如果我发现解决方案中存在重大缺陷,请告知我。干杯不,我提供的解决方案是故意的过度使用。我们的想法是提供所有部件,让您了解系统,然后选择适合您的部件。看来你确实做到了。:-)