如何在数组中存储循环数字?

时间:2015-11-05 07:15:28

标签: arrays excel vba

我有一个循环遍历工作表中每行数据的程序。行包含数字。我想存储在数组变量中找到的所有数字,然后将每个数字与最高和最低进行比较。

但我不知道如何自动将数字存储在数组中。

2 个答案:

答案 0 :(得分:0)

不要将它们存储在阵列中,但要检查最小/最大的动态!

Sub test()

dim max As Double, min As Double
dim r As Range, rng As Range

Set rng = Range("A1","A10")' Set this to the appropriate range
min = rng(1).Value
max = rng(1).Value

For each r in rng

If r.Value > max Then

max = r.Value

Elseif r.Value < min Then

min = r.Value

End If
Next r

Range("B1").Value = max ' store where ever you want
Range("B2").Value = min 'same as above

End Sub

答案 1 :(得分:0)

有更简单的方法可以获得空行,文本和数字行中的最小值和最大值,但这里是将行中的数字收集到变量数组中的示例。

Sub minmax()
    Dim r As Long, c As Long, n As Long, vNUMs As Variant
    Dim mn As Double, mx As Double

    With Worksheets("Sheet2")
        For r = 2 To .Cells(Rows.Count, 2).End(xlUp).Row

            'you can do this the easy way
            mx = Application.Max(.Rows(r))
            mn = Application.Min(.Rows(r))
            Debug.Print mn & " to " & mx

            'or the hard way
            n = 0
            ReDim vNUMs(Application.Count(.Rows(r)) - 1)
            For c = 1 To .Cells(r, Columns.Count).End(xlToLeft).Column
                If IsNumeric(.Cells(r, c)) And Not IsEmpty(.Cells(r, c)) Then
                    vNUMs(n) = .Cells(r, c).Value2
                    n = n + 1
                    If n > UBound(vNUMs) Then Exit For
                End If
            Next c

            mx = -2 ^ 20
            mn = 2 ^ 20
            For n = LBound(vNUMs) To UBound(vNUMs)
                If vNUMs(n) < mn Then mn = vNUMs(n)
                If vNUMs(n) > mx Then mx = vNUMs(n)
            Next n
            Debug.Print mn & " to " & mx
        Next r
    End With
End Sub