在子例程Excel VBA之间传递二维数组

时间:2018-07-29 09:10:12

标签: excel vba subroutine

我似乎无法使它正常工作。

我想将2D数组从子例程传递到应该进行数据操作的其他子例程。

我正在通过 Sheet1 上的命令按钮在下面的子例程中调用。在 Module1 中,我已将变量声明为public。在子例程ReadData中,在End If语句中,InputArray填充有一个数组,该数组由用户在输入框后标记的数字组成。子例程ReadData完成后,InputArray为空。

我做错了什么显而易见的愚蠢的事?

** Sheet1**:
Private Sub CommandButton1_Click()
    Call ReadData
End Sub

**Module1**:
Option Explicit
Option Base 1
Public MyRange, InputArray As Variant

Sub ReadData()
    Set MyRange = Application.InputBox("Mark the data array", Type:=8)
    If Not MyRange Is Nothing Then
        InputArray = MyRange
    End If
End Sub 

3 个答案:

答案 0 :(得分:1)

按如下所示填充数组并在locals窗口中检查。通过使用.Value,可以从选定的图纸范围创​​建2D数组。我认为MyRange可以是局部范围,并声明为Range。 InputArray可能也应该是局部作用域,并只是作为参数传递给其他子功能。

Public InputArray As Variant

Sub ReadData()
    Dim MyRange As Range
    Set MyRange = Application.InputBox("Mark the data array", Type:=8)
    If Not MyRange Is Nothing Then
        InputArray = MyRange.Value
        Stop '<==Delete me after inspection
    End If
End Sub

Sheet

答案 1 :(得分:1)

完全不需要公共变量。

option explicit

'** Sheet1**:
Private Sub CommandButton1_Click()
    dim InputArray as variant, i as long, j as long

    ReadData InputArray 

    for i = lbound(InputArray, 1) to ubound(InputArray, 1)
        for j = lbound(InputArray, 2) to ubound(InputArray, 2)
            debug.print InputArray(i, j)
        next j
    next i

End Sub

'**Module1**:
Option Explicit

Sub ReadData(byref arr as variant)
    dim myrange as range

    Set MyRange = Application.InputBox("Mark the data array", Type:=8)

    If Not MyRange Is Nothing Then
        arr  = MyRange.value
    End If

End Sub 

enter image description here

 1 
 4 
 7 
 10 
 2 
 5 
 8 
 11 
 3 
 6 
 9 
 12 

答案 2 :(得分:0)

沿着@Jeeped的方法,您可以通过将ReadData()转换为Function来简化代码,如下所示:

Sheet1

Function ReadData() As Variant
    On Error Resume Next
    ReadData = Application.InputBox("Mark the data array", Type:=8).Value
End Function

Module1

Option Explicit
Private Sub CommandButton1_Click()
    Dim InputArray As Variant

    InputArray = ReadData

    If IsEmpty(InputArray) Then
        MsgBox "not a valid selection", vbCritical
    Else
        'do your stuff with InputArray
    End If
End Sub

或者您可以让ReadData()函数返回Boolean来标记成功进行范围选择:

Sheet1

Function ReadData(arr As Variant) As Boolean
    On Error Resume Next
    arr = Application.InputBox("Mark the data array", Type:=8).Value
    ReadData = Not IsEmpty(arr)
End Function

Module1

Option Explicit

Private Sub CommandButton1_Click()
    Dim InputArray As Variant

    If ReadData(InputArray) Then
        'do your stuff with InputArray
    Else
        MsgBox "not a valid selection", vbCritical
    End If        
End Sub