我正在研究一个vba函数来计算一系列数据除以另一个数据的最大值。所有似乎都运行良好,但在尝试将Application.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
答案 0 :(得分: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_D
和x_S
数组即可读取所有值。