在VBA Excel中的不同Subs中引用相同的数组

我有一个函数,根据select哪个选项button来填充单元格的某个数组。 我将如何在一个单独的函数中引用这些相同的数组,将这些值反馈到单元格中? 这是我的(工作)代码到目前为止。

Private Sub CommandButton1_Click() Dim wave1Array(0 To 30) As String Dim wave2Array(0 To 30) As String Dim wave3Array(0 To 30) As String Dim wave4Array(0 To 30) As String Dim wave5Array(0 To 30) As String Dim rng As Range Dim cell As Range Dim counter As Long Set rng = Range("B2", "AF2") counter = 0 If OptionButton6.Value = True Then For Each cell In rng wave1Array(counter) = cell.Value counter = counter + 1 Next cell ElseIf OptionButton7.Value = True Then For Each cell In rng wave2Array(counter) = cell.Value counter = counter + 1 Next cell ElseIf OptionButton8.Value = True Then For Each cell In rng wave3Array(counter) = cell.Value counter = counter + 1 Next cell ElseIf OptionButton9.Value = True Then For Each cell In rng wave4Array(counter) = cell.Value counter = counter + 1 Next cell ElseIf OptionButton10.Value = True Then For Each cell In rng wave5Array(counter) = cell.Value counter = counter + 1 Next cell End If End Sub 

我可以想到几个不同的选项。

正如其他人所提到的,根据需要创build一个模块级别的variables。 这些声明应该放在与您的表单控件相同的代码模块中。 如果表单控件位于用户窗体上,则应在窗体的代码模块中声明它们,而不是“标准”模块。

 '-------------------------------- all in the same code module ------------- Option Explicit Dim myVariable as String Private Sub CommandButton1_Click() myVariable = "Hello, world!" End Sub Private Sub CommandButton2_Click() msgBox myVariable End Sub '------------------------------- end of this example ---------------------- 

公/ GLOBALvariables可能是一个选项,但我记得有一些使用UserForms这些限制,因为我不知道如果您使用UserForm,我不会build议。

第三种select是将参数从一个过程传递到另一个过程,但通常只能在“链接”过程/函数中起作用,就像一个函数调用另一个函数一样,而这看起来并不是你所做的。

对于您的具体情况:

您还可以简化代码,避免使用countercellvariables,使用直接的范围到数组赋值。

 'Module-level array variables, accessible by other procedures in this module: Dim wave1Array() Dim wave2Array() Dim wave3Array() Dim wave4Array() Dim wave5Array() Dim wave6Array() Private Sub CommandButton1_Click() Dim rng As Range Dim arr() Set rng = Range("B2", "AF2") '## Converts the row to an array (0 to 30) arr = Application.Transpose(Application.Transpose(rng.Value)) '## Assigns the array from above to one of the module-level array variables: If OptionButton6.Value = True Then wave1Array = arr If OptionButton7.Value = True Then wave2Array = arr If OptionButton8.Value = True Then wave3Array = arr If OptionButton9.Value = True Then wave4Array = arr If OptionButton10.Value = True Then wave5Array = arr If OptionButton11.Value = True Then wave6Array = arr End Sub 

请注意 ,要做到这一点,你将不得不声明他们作为变体数组,因为一个单元格的范围.Value是一个变体types(单元格可以包含错误值,我认为将失败,如果您尝试分配给一个string数组)。

如果你必须使用严格的string数组,那么你将需要使用countercell迭代。