如何将范围值存储到数组中,然后在VBA中将它们联合起来?

时间:2016-06-15 10:00:48

标签: arrays vba excel-vba excel

我在VBA中比较新,但仍然无法按照我想要的方式操作范围和数组值。

我正在构建一个用户表单,我希望能够将用户提供的两个范围的值组合在一个数组中,以便对它们进行排序,然后使用它们构建统计测试(Wilcoxon)。我正在努力做第一部分。我尝试了不同问题的多次变换,但似乎没有任何效果。

这是我到目前为止的地方:

Private Sub OK_Click()
    Dim range1 As Range
    Dim range2 As Range

    Dim k As Integer
    'Sample1 and 2 provided by the user
    Set range1 = Range(Sample1.Value)
    Set range2 = Range(Sample2.Value)

    n = Application.Count(range1)
    m = Application.Count(range2)

    Dim arr1() As Variant
    ReDim arr1(1 To n)
    Dim arr2() As Variant
    ReDim arr2(1 To m)
    Dim unionarr() As Variant
    ReDim unionarr(1 To n + m)
    Dim x As Variant
    'store the range values in two arrays
    arr1 = range1
    arr2 = range2
    'combine (unite) the two arrays in a new array
    For k = 1 To n
        unionarr(k) = arr1(k)
        Next k

    For k = n + 1 To n + m
        unionarr(n + k) = arr2(k)
        Next k
End Sub

2 个答案:

答案 0 :(得分:0)

Private Sub OK_Click()
    Dim range1 As Range
    Dim range2 As Range
    Dim vArr1 As Variant
    Dim vArr2 As Variant
    Dim vCombined() As Variant
    Dim lComb As Long
    Dim lRow As Long
    Dim lCol As Long
    'Sample1 and 2 provided by the user
    Set range1 = Range(Sample1.Value)
    Set range2 = Range(Sample2.Value)
    vArr1 = range1.Value2
    vArr2 = range2.Value2
    'Assuming same # of columns in both ranges!
    ReDim vCombined(LBound(vArr1, 1) To UBound(vArr1, 1) + UBound(vArr2, 1), LBound(vArr1, 2) To UBound(vArr1, 2))
    For lRow = LBound(vArr1, 1) To UBound(vArr1, 1)
        For lCol = LBound(vArr1, 2) To UBound(vArr1, 2)
            lComb = lComb + 1
            vCombined(lComb, lCol) = vArr1(lRow, lCol)
        Next
    Next
    For lRow = LBound(vArr2, 1) To UBound(vArr2, 1)
        For lCol = LBound(vArr2, 2) To UBound(vArr2, 2)
            lComb = lComb + 1
            vCombined(lComb, lCol) = vArr2(lRow, lCol)
        Next
    Next
End Sub

答案 1 :(得分:0)

Sub test()

Dim r1 As Range
Dim r2 As Range
Dim r3 As Range
Dim c As Range
Dim a() As Double
Dim iCounter As Integer

Set r1 = Range("a1:a10")
Set r2 = Range("c1:c10")

Set r3 = Union(r1, r2)

ReDim a(r3.Cells.Count)

iCounter = 0

For Each c In r3.Cells
    a(iCounter) = c.Value
    iCounter = iCounter + 1
Next c

End Sub