查找值,将其放入数组中并找到数组VBA中的最小值

时间:2016-03-03 15:23:00

标签: arrays vba excel-vba dynamic-arrays excel

我想在一个范围内找到一个给定的值,如果我找到了值,我想把它放在一个数组中。在循环之后,我想将数组中的最小值赋给变量。

怎么可能?

    For k = 2 To LastRow_Roles
        If roles_sheet.Cells(k, 2).Value = "Admin" Then
            selected_number = roles_sheet.Cells(k, 1).Value
            ReDim aArray(0 To UBound(aArray) + 1) As Variant
            aArray(UBound(aArray)) = selected_number        
         end if
    next k

minimum_value = Application.min(aArray)
low_sheet.Cells(1, 1) = minimum_value
Erase aArray
ReDim aArray(0 To 1) As Variant

1 个答案:

答案 0 :(得分:1)

您需要使用ReDim Preserve,以便保留已附加到阵列的现有数据。

然后,您可以使用Application.WorksheetFunction.Min函数提取数组中找到的Min数字。

For k = 2 To LastRow_Roles
    If roles_sheet.Cells(k, 2).Value = "Admin" Then
        ReDim Preserve aArray(0 To UBound(aArray) + 1)
        aArray(UBound(aArray)) = roles_sheet.Cells(k, 1).Value
    End If
Next k

minimum_value = Application.WorksheetFunction.Min(aArray)
low_sheet.Cells(1, 1) = minimum_value
Erase aArray
ReDim aArray(0 To 1) As Variant