[转]Excel⾃定义数组公式
原⽂链接:
我们⾃定义的返回数组的函数,跟 Excel ⾃带的数组函数⼀样,需要按 Ctrl+Shift+Enter 输⼊。
在返回数组这件事上,我们需要决定返回的数组的维度。有下⾯⼏种情况:
第⼀种情况,返回⼀个⼤⼩固定的数组。
Function FixedFill() As Variant
Dim N As Long
Dim R As Long
Dim C As Long
N = 0
Dim V(1To3, 1To4)
For R = 1To3
For C = 1To4
N = N + 1
V(R, C) = N
Next C
Next R
FixedFill = V
End Function
这个函数返回⼀个 3x4 ⼤⼩的数组,值从 1 到 12。但是这个函数并没有什么应⽤价值,我们的返回值还是应该根据传⼊的参数或者输⼊函数的单元格范围的⼤⼩来变化。
第⼆种情况,根据输⼊函数的单元格范围⼤⼩来变化。也就是说,如果选了 A1:B2 这样 2x2 的范围来输⼊我们⾃定义的函数,我们返回的数组就是 2x2 ⼤⼩;如果选了 C3:E8 这样 6x3 的范围来输⼊我们⾃
定义的函数,我们返回的数组就是 6x3 ⼤⼩。要获得输⼊函数的单元格范围的⼤⼩,我们可以⽤Application.Caller 这个属性。当我们从表单单元格⾥调⽤函数时,Application.Caller 属性返回的是⼀个 Range 对象引⽤,表⽰输⼊该函数的单元格范围。
Function DynamicFill() As Variant
Dim CallerRows As Long
Dim CallerCols As Long
Dim Result() As Long
Dim N As Long
Dim i As Long
Dim j As Long
N = 0
With Application.Caller
CallerRows = .Rows.Count
CallerCols = .Columns.Count
End With
ReDim Result(1To CallerRows, 1To CallerCols)
For i = 1To CallerRows
For j = 1To CallerCols
N = N + 1
Result(i, j) = N
Next j
Next i
DynamicFill = Result
End Function
第三种情况,结合传⼊的参数和函数的⽬的来决定返回数组的维度。像我前⼀篇⽂章⾥的 MySum 函数,传⼊的虽然是个参数数组,但返回唯⼀的值。我这⾥举的⼀个例⼦,返回的数组⼤⼩根据传⼊的参数范围⽽变化。这个⾃定义函数是⽤来排序的,⽐如对员⼯年龄,学⽣分数等等。期望的参数是⾄少两列的单元格范围,参数的第⼀列是标识符,⽐如姓名,⼯号等等,参数的最后⼀列是要排序的数值。返回的数组为两列,⾏数根据传⼊的参数变化。返回数组的第⼀列即传⼊参数的第⼀列,返回数组的第⼆列即传⼊参数的最后⼀列,返回的数组⾥⾯的数据已经排过序。
Function MySort(cells As Range)
Dim x As Integer
Dim y As Integer
Dim i As Integer
Dim j As Integer
Dim workCells()
x = cells.Rows.Count
y = cells.Columns.Count
ReDim workCells(1To x, 1To2)
For i = 1To x
workCells(i, 1) = cells(i, 1)
workCells(i, 2) = cells(i, y)
Next i
Dim temp
For i = 2To x
temp = workCells(i, 2)
j = i - 1
Do While (workCells(j, 2) > temp)
workCells(j + 1, 2) = workCells(j, 2)
excel函数数组公式编辑方法workCells(j + 1, 1) = workCells(j, 1)
j = j - 1
If j < 1Then
Exit Do
End If
Loop
workCells(j + 1, 2) = cells(i, y)
workCells(j + 1, 1) = cells(i, 1)
Next i
MySort = workCells
End Function
最后补充⼀下,返回的数组应该定义为两维的,单维的数组在填充单元格的时候有问题。

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。