返回一個變量大小結果數組的方法
此方法返回基於一個參數范圍的值的數組。結果數組的大小具體取決於參數數組中的元素數量波動。例如對於假定您要創建一個范圍中的每個值乘以 100 的函數。下面的自定義函數接受作為其參數的數組 (某一范圍的值):
Function Multiply_Range(myrange As Object) As Variant
Dim temp As Variant
Dim i As Integer, j As Integer
temp = myrange.Value 'creates a copy of the values in myrange
' if more than one element then loop through both dimensions of
' the array and multiply each element by 100.
' if not more than one element then temp is multiplied by 100.
If IsArray(temp) Then
For i = 1 To UBound(temp, 1)
For j = 1 To UBound(temp, 2)
temp(i, j) = temp(i, j) * 100
Next j
Next i
Else
temp = temp * 100
End If
Multiply_Range = temp
End Function
若要用於自定義函數中的單元格 A1:A4 中輸入以下數據:
A1:
5
A2: 3
A3: 1
A4: 2
A2: 3
A3: 1
A4: 2
選擇范圍 B1:B4 並以數組形式輸入以下公式:
=Multiply_Range(A1:A4)
注意: 上述公式必須以數組公式的形式輸入。若要將公式作為數組公式,在 Excel 中輸入 windows,請按 CTRL + SHIFT + ENTER。在 Excel 中為 Macintosh,請按命令 + ENTER。
結果將是:
A1: 5 B1: 500 A2: 3 B2: 300 A3: 1 B3: 100 A4: 2 B4: 200
要返回的固定大小數組結果的方法
此方法從自定義函數返回多個值假定您在所得數組中已經輸入固定的個數的元素。
下面的自定義函數接受起始時間和結束時間,並返回它們在 3 行 1 列數組之間的小時、 分鍾和秒數。 >
Function Elapsed_Time(start, finish As Date) As Variant
Dim hours, minutes, seconds As Integer
hours = Hour(finish - start)
minutes = Minute(finish - start)
seconds = Second(finish - start)
Elapsed_Time = Application.Transpose(Array(hours, minutes, seconds))
End Function
若要用於此自定義的函數 (例如對於 A1 和 A2 下面) 的兩個單元格中輸入開始時間和完成時間。
A1:
1: 00: 00
A2: 6:49:34
A2: 6:49:34
然后,突出顯示的列 (例如對於到 A5 A3) 中的三個單元格,並以數組公式的形式輸入以下內容:
=Elapsed_Time(A1,A2)
注意: 上述公式必須以數組公式的形式輸入。若要將公式作為數組公式,在 Excel 中輸入 windows,請按 CTRL + SHIFT + ENTER。在 Excel 中為 Macintosh,請按命令 + ENTER。
該結果將顯示,如下所示:
A1: 1:00:00 A2: 6:49:34 A3: 5 A4: 49 A5: 34
如果您希望該函數輸入水平代替垂直的單元格區域,更改 Elapsed_Time 該行在以讀取行:
elapsed_Time = 陣列 (小時、 分鍾、 秒)
