在Array Excel VBA中返回Min值的索引

时间:2016-09-23 03:51:56

标签: arrays excel vba find

我正在尝试从sum(3)数组中找到最小值的索引。它应该分配给变量 min

min = 最小值索引

我应该先对数组进行排序,还是有直接的方法呢? 这是我的代码:

 `Sub Min_index()
        Dim Pt_array(3) As Single
        Pt_array(0) = 0
        Pt_array(1) = 12.3
        Pt_array(2) = 16.06
        Pt_array(3) = 20.11

        Dim Ad_E_array(3) As Single
        Dim Lo_E_array(3) As Single
        Dim Bs_temp As Single

        Dim i As Integer
        i = 0
        Do While i < 4
            Bs_temp = BS
            Ad_E_array(i) = Ad_E    'defined in previous Sub
            Lo_E_array(i) = Lo_E    'defined in previous Sub

            If Bs_temp + Pt_array(i) - Qth < BS_Maximum_limit Then
                Bs_temp = Bs_temp + Pt_array(i) - Qth
                Ad_E_array(i) = Ad_E_array(i) + 0
                Lo_E_array(i) = Lo_E_array(i) + 0
                Call function_decide(int_forecast_hour - 1, Bs_temp, Qth + 1, Lo_E_array(i), Ad_E_array(i))
            Else
                Lo_E_array(i) = Pt_array(i) - Qth - (BS_Maximum_limit - Bs_temp)
                Bs_temp = BS_Maximum_limit
                Call function_decide(int_forecast_hour - 1, Bs_temp, Qth + 1, Lo_E_array(i), Ad_E_array(i))
            End If
        i = i + 1
        Loop

        Dim sum(3) As Single
        Dim min As Single
        i = 0
        Do While i < 4
        sum(i) = Abs(Lo_E_array(i)) + Abs(Ad_E_array(i))
        i = i + 1
        Loop
  End Sub`  

1 个答案:

答案 0 :(得分:2)

您可以使用Excel Application object使用工作表的MIN functionMATCH function来接收包含最小值的元素的从1开始的索引位置。

Sub wqewuiew()
        Dim Pt_array(3) As Single, p As Long
        Pt_array(0) = 1000
        Pt_array(1) = 12.3
        Pt_array(2) = 16.06
        Pt_array(3) = 20.11

        p = Application.Match(Application.Min(Pt_array), Pt_array, 0)

        Debug.Print p   '<~~ 'p' is 2 (I changed the value of the first array element)
End Sub