1.基礎結構
1.1 定義
Function,相當于在VBA里新增一個自定義函數(shù),這個函數(shù)可以在工作、VBA代碼里直接使用
1.2 規(guī)范語句
[Public][Private][Static] Function 函數(shù)名 ([參數(shù)列表]) [As 數(shù)據(jù)類型]
[語句塊]
[函數(shù)名 = 過程結果]
[Exit Function]
[語句塊]
[函數(shù)名 = 過程結果]
End Function
1.3 使用函數(shù)
跟其他excel函數(shù)一樣,直接使用即可
在VBA過程中,也可以使用Function自定義函數(shù),用法一樣
2.案例:隨機函數(shù)
需求:新建1個函數(shù),可以生成1~10之間的隨機整數(shù)
Public Function fun()
fun = Int(Rnd() * 10) +1 'Rnd()等同于工作表里的Rand()函數(shù)
End Function
3.案例:統(tǒng)計指定顏色的單元格數(shù)量
需求:統(tǒng)計出下圖中,黃色單元格的數(shù)量

image.png
黃色的RGB編碼是 (255,255,0),代碼過程:
Public Function CountColor()
Dim rng As Range
For Each rng In Range("A1:D12")
If rng.Interior.Color = RGB(255, 255, 0) Then
CountColor = CountColor + 1
End If
Next rng
End Function
4.使用參數(shù)來指定計算區(qū)域
在使用函數(shù)的時候,填入?yún)^(qū)域參數(shù)即可 : CountColor(A:V)
Public Function CountColor(arr As Range)
Dim rng As Range
For Each rng In arr
If rng.Interior.Color = RGB(255, 255, 0) Then
CountColor = CountColor + 1
End If
Next rng
End Function
5.設置易失性
定義:帶有"易失性"屬性的函數(shù),在工作表重算時,函數(shù)也會跟著重新計算
Public Function fun()
Application.Volatile True '設置易失性
fun = Int(Rnd() * 10) +1 'Rnd()等同于工作表里的Rand()函數(shù)
End Function