0

我正在研究一个 vba 函数来计算一个数据范围的最大值除以另一个数据。一切似乎都运行良好,但是在尝试对数组执行 Application.Max 时似乎存在问题,我通过循环解决了它。但是我无法回忆循环外的 Max 值...第一个 Debug.Print 正常打印 MaxV 值,但是第二个 [循环外] Debug.Print MaxV 没有任何结果。CalDS2 函数得到一个#VALUE!错误。

Function CalDS2(RangeD As Range, RangeS As Range, MaxMin As String) As Variant    
Dim i As Integer
Dim ArrayDS() As Variant
Dim MaxV As Variant
Dim MinV As Variant
MaxV = 0
MinV = 1000000000
For i = 1 To RangeD.Columns.Count
    ArrayDS(i) = Round(RangeD.Cells(1, i) / RangeS.Cells(1, i), 4)
    If ArrayDS(i) >= MaxV Then
        MaxV = ArrayDS(i)
        Debug.Print MaxV
    End If
Next i
Debug.Print MaxV
CalDS2 = MaxV
End Function

任何帮助将不胜感激,安迪

** * ***新代码* ** * *

Function CalDS2(RangeD As Range, RangeS As Range, MaxMin As String) As Variant
    Dim i As Long
    Dim ArrayD, ArrayS, ArrayDS() As Variant
    If UCase(MaxMin) <> "MAXIMUM" And UCase(MaxMin) <> "MINIMUM" Then
        MsgBox "The 3rd argument - MaxMin - must be either Maximun or Mininum"
        CalDS2 = "Error"
        Exit Function
    End If

    ReDim ArrayDS(1 To RangeD.Columns.Count)
    ArrayD = RangeD.Value
    ArrayS = RangeS.Value
    For i = 1 To RangeD.Columns.Count
        ArrayDS(i) = ArrayD(1, i) / ArrayS(1, i)
        Debug.Print ArrayDS(i)
    Next i

    If UCase(MaxMin) = "MAXIMUM" Then
        CalDS2 = WorksheetFunction.Max(ArrayDS)
    Else
        CalDS2 = WorksheetFunction.Min(ArrayDS)
    End If
End Function
4

1 回答 1

0

尝试这个:

Public Enum Op
    Minimum = 1
    Maximum = 2
End Enum

' Call by "=CalDS2(B2:F2,B3:F3,2)"
Public Function CalDS2(r_D As Range, r_S As Range, MinMax As Op) As Double

    Dim x_D() As Variant, x_S() As Variant, x_DS() As Variant

    x_D = r_D.Value2
    x_S = r_S.Value2

    Dim i As Integer, N As Integer, res As Double

    N = r_D.Columns.Count
    ReDim x_DS(1 To N)

    For i = 1 To N
        x_DS(i) = x_D(1, i) / x_S(1, i)
    Next i

    res = x_DS(1)

    For i = 2 To N
        If (MinMax = Maximum And x_DS(i) > res) _
        Or (MinMax = Minimum And x_DS(i) < res) Then
            res = x_DS(i)
        End If
    Next i

    CalDS2 = res
End Function

它比调用内置函数要快得多,并且您只需扫入x_Dx_S数组即可读取所有值。

于 2013-06-24T16:45:11.243 回答