如何将A1:A500等数组数据传递给Excel用户定义函数

时间:2017-09-15 20:56:01

标签: excel excel-vba excel-formula user-defined-functions vba

我正在尝试将变量数组传递给excel用户定义的函数。我的Excel VBA附在下面,我希望我可以将A1:A100等范围传递到当前变量Data中,然后像普通的excel公式一样操作它。非常感谢任何帮助。

 Function LowerB_4n_2(inputrange As Range) As Double
 Dim myArray As Variant
 Data = inputrange.Value
 LowerB_4n_2 = Small(Data, (Round((((0.4 * (Count(Data))) - 2)), 0)))
 End Function

 Function UpperB_4n_2(inputrange As Range) As Double
 Dim myArray As Variant
 Data = inputrange.Value
 UpperB_4n_2 = Large(Data, (Round((((0.4 * Count(Data)) - 2)), 0)))
 End Function

 Function Width4n_2(inputrange As Range) As Double
 Dim myArray As Variant
 Data = inputrange.Value
  Width4n_2 = (Large(Data, (Round((((0.4 * Count(Data)) - 2)), 0))) - 
  (Small(Data, (Round((((0.4 * Count(Data)) - 2)), 0)))))

  End Function

1 个答案:

答案 0 :(得分:1)

大,小和计数都是Application.WorksheetFunction的所有属性,因此他们需要将该集合作为其父级。

只是你的第一个:

 Function LowerB_4n_2(inputrange As Range) As Double
 Dim data() As Variant
 data = inputrange.Value
 LowerB_4n_2 = Application.WorksheetFunction.Small(data, (Round((((0.4 * (Application.WorksheetFunction.Count(data))) - 2)), 0)))
 End Function

根据评论,

由于大小都已经过简化,因此没有理由将范围值传递给数组。我们可以在公式中引用范围对象:

 Function LowerB_4n_2(inputrange As Range) As Double
 LowerB_4n_2 = Application.WorksheetFunction.Small(inputrange, (Round((((0.4 * (Application.WorksheetFunction.Count(inputrange))) - 2)), 0)))
 End Function

 Function UpperB_4n_2(inputrange As Range) As Double
 UpperB_4n_2 = Application.WorksheetFunction.Large(inputrange, (Round((((0.4 * (Application.WorksheetFunction.Count(inputrange))) - 2)), 0)))
 End Function

 Function Width4n_2(inputrange As Range) As Double
 With Application.WorksheetFunction
     Width4n_2 = .Large(inputrange, (Round((((0.4 * .Count(inputrange)) - 2)), 0)) - .Small(inputrange, (Round((((0.4 * .Count(inputrange)) - 2)), 0))))
 End With