繁体   English   中英

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

[英]Referencing the same array in different Subs in VBA Excel

我有一个函数,该函数使用选定的OptionButton来用单元格值填充特定数组。 我将如何在单独的函数中引用这些相同的数组,这些函数会将这些值反馈回单元格中? 到目前为止,这是我的(有效)代码。

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

您可以想到几种不同的选择。

正如其他人提到的那样,根据需要制作一个模块级变量。 这些声明应与表单控件放在同一代码模块中。 如果表单控件位于用户表单上,则应在表单的代码模块(而不是“标准”模块)中声明它们。

'-------------------------------- 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 ----------------------

可以选择使用Public / GLobal变量,但是我记得在UserForms中使用这些变量存在一些限制,并且由于我不确定您是否在使用UserForm,因此不建议这样做。

第三种选择是将参数从一个过程传递到另一个过程,但这通常仅适用于“链接”过程/函数,例如当一个函数调用另一函数时,这似乎根本就不是您正在做的事情。

对于您的具体情况:

您还可以简化代码,避免使用countercell变量,而是使用直接范围到数组的分配。

'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是变量类型(单元格可能包含错误值,如果您尝试分配给字符串数组,这些错误值我相信会失败)。

如果必须使用严格的String数组,则需要使用countercell迭代。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM