用户定义的函数,用于在VBA 2010中模拟Max.ifs

时间:2016-12-06 23:10:56

标签: vba excel-vba excel

我正在尝试创建一个函数来计算基于2个条件的范围的最大值,就像Excel的2016函数(MAX.IFS)一样,据我所知我做得很好但它返回#VALUE错误。

你能帮帮我吗?

Option Base 1
Function MaxIf(RangoUno As Range, RangoDos As Range, RangoTres As Range, RUno As Variant, RDos As Variant) As Variant
Dim x() As Variant, y() As Variant, z() As Long, w() As Long
Dim i As Long
Dim ConstraintUno As Variant, ConstraintDos As Variant, k As Long
i = 1
k = 0
ConstraintUno = RUno
ConstraintDos = RDos
 x = RangoUno 'Rango que contiene la primera restricción
 y = RangoDos  'Rango que contiene la segunda restricción
 z = RangoTres 'Rango que contiene los valores numericos
  For i = 1 To RangoUno.Rows.Count
   If x(i, 1) = RUno Then
    If y(i, 1) = RDos Then
    k = k + 1
    ReDim Preserve w(k, 1)
     w(k, 1) = z(i, 1) ' w() es una matriz que almacena los valores numericos en cuya fila cumpla con las rectricciones 1 y 2
      End If
    End If
   Next i
MaxIf = application.max(w)
End Function

1 个答案:

答案 0 :(得分:3)

修复代码有两件事:

1)将z() as long更改为z() as Variant

2)你不能redim w你做的方式(使用2D数组)。但是,您可以通过将w设为一维数组来避免这种麻烦,因为您只需在其中保留简单值即可调用Application.Max ...

 ReDim Preserve w(k)
 w(k) = z(i, 1)
 ....
 MaxIf = application.max(w)

在这些变化之后,UDF对我有用。