日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

VBA函数定义及说明

發(fā)布時間:2023/12/9 编程问答 34 豆豆
生活随笔 收集整理的這篇文章主要介紹了 VBA函数定义及说明 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

文章目錄

  • 函數(shù)定義
  • 傳值和傳引用
  • 函數(shù)返回對象
  • 使用默認參數(shù)
  • 使用不定長參數(shù)
  • 一些函數(shù)示例
    • text_split:字符串分割
    • file_exists:判斷文件是否存在
    • basename:路徑提取文件名
    • sheet_exists:工作表是否存在
    • workbook_is_open:工作表是否存在
    • text_join:split的反函數(shù)
    • ifs:多判斷
    • range_workbook_name:返回單元格所在的工作簿名稱
    • text_speak:說出文本
    • is_like:模式匹配

函數(shù)定義

VBA定義的函數(shù)可以在工作表使用,如果是在加載插件中定義函數(shù),本機所有打開工作簿都可以使用該函數(shù),當然可以在過程sub中調(diào)用函數(shù);

VBA函數(shù)與sub過程不同的是,函數(shù)有返回內(nèi)容;過程和函數(shù)都可以傳入?yún)?shù)。
函數(shù)使用Function關(guān)鍵字定義,定義規(guī)則如下:
Function 函數(shù)名稱(形參及類型)
函數(shù)主體
函數(shù)名稱= 函數(shù)返回
End Function
示例:

'定義一個數(shù)值平方的函數(shù),形參:a,形參a類型:long,函數(shù)返回:a ^ 2;函數(shù)名稱:test Function test(a as long) test = a ^ 2 End Function'定義全局函數(shù),使用public關(guān)鍵字,這個關(guān)鍵字跟變量定義是一致的。后面跟的as long是返回類型 Public Function test(a as long) as long test = a ^ 2 End Function

傳值和傳引用

函數(shù)或方法傳值使用關(guān)鍵字ByVal,傳引用使用關(guān)鍵字ByRef

Sub num_print() Dim i, num As Long ' 定義一個變量 num = 0 For i = 1 To 10s = add(num) ' 調(diào)用add函數(shù)sDebug.Print num ' 函數(shù)參數(shù)是傳引用,會依次打印1,2,3,,,,10 Next End SubFunction add(ByRef a As Variant) a = a + 1 End Function

如果上述函數(shù)參數(shù)為傳值ByVal,則函數(shù)不影響方法num_print中變量num的改變,全打印0;

函數(shù)返回對象

函數(shù)也可以返回對象,返回對象要使用set關(guān)鍵字;
示例:返回字典

Function aa() Dim d As ObjectSet d = CreateObject("scripting.dictionary") today = Date the_month_date = CDate(Year(Date) & "-" & Month(Date) & "-" & 20) '這個月的20號 last_month_date = Application.WorksheetFunction.EDate(the_month_date, -1) '上個月的20號 d("today") = today d("the_month_date") = the_month_date d("last_month_date") = last_month_date d("the_month") = Month(last_month_date) '這個月 d("last_month") =Month(Date) '上個月Set aa = d '返回對象使用set關(guān)鍵字 End Function'函數(shù)調(diào)用 sub test1() dim d1 as objectset d1 = aa() debug.print d1("today") '打印字典鍵today對應的值 end sub

使用默認參數(shù)

函數(shù)傳入?yún)?shù)格式:形參 as 參數(shù)類型 = 參數(shù)默認值
示例:正則提取函數(shù)

Function regexp(rg As Variant, str As String, Optional mat As Byte = 0, Optional group As Variant = Empty) 'Optional表示參數(shù)不是必需的關(guān)鍵字。如果使用了該選項,則參數(shù)表中該參數(shù)后的參數(shù)都必須是可選的,而且必須都使用 Optional 關(guān)鍵字聲明。 Dim re As Object Set re = CreateObject("vbscript.regexp")With re.Global = True.Pattern = strIf re.test(rg) ThenIf group = Empty Thenregexp = re.Execute(rg)(mat)Elseregexp = re.Execute(rg)(mat).submatches(group)End IfEnd IfEnd With Set re = Nothing End Function

使用不定長參數(shù)

形參及類型固定寫法:ParamArray 參數(shù)名稱() As Variant(必須放在參數(shù)最后面)
示例:只要有一個單元格為空,返回空字符串

Function if_blank(goal_rg As Variant, ParamArray rngs() As Variant) Dim rg For Each rg In rngsIf rg.Value = "" Thenif_blank = ""Exit FunctionEnd If Next if_blank = goal_rg End Function

示例:單元格求和sum

Function rng_sum(ParamArray values() As Variant) Dim result As Variant Dim val0 As Variant ' for循環(huán)里的變量必須是變體型變量,否則會報錯 result = 0 For Each val0 In valuesFor Each val1 In val0result = result + val1Next Next rng_sum = result End Function'然后我們在工作表里寫了這么一個函數(shù) =rng_sum(K21:L21,M22:N22,L23:N23)

一些函數(shù)示例

text_split:字符串分割

EXCEL里面沒有split函數(shù),可以使用vba定義該函數(shù),在工作表內(nèi)使用

Function text_split(str As String, sep As String, index As Long) ' 參數(shù):str:被分割的字符串,sep:分隔符,index:分割后返回數(shù)組該索引的值,如果小于0返回數(shù)組 ' 樣例:text_split("abc,de,fg",",")(1) 返回:deIf index >= 0 Thentext_split = Split(str, sep)(index) Elsetext_split = Split(str, sep) End If End Function

file_exists:判斷文件是否存在

判斷文件是否存在,dir函數(shù)可以使用通配符:*

Function file_exists(full_name As String) As Boolean file_exists = (Dir(full_name) <> "") End Function

basename:路徑提取文件名

傳入一個帶路徑完整的文件名,返回文件名,比如:test.xlsx

Function basename(full_name) ' Application.PathSeparator:反斜杠 ' basename("d:/filedir/text.xlsx"),返回:text.xlsx Dim arr As Variant arr = Split(full_name, Application.PathSeparator) basename = arr(UBound(arr)) End Function

sheet_exists:工作表是否存在

Function sheet_exists(sheet_name As Variant) As Boolean ' 傳入工作表名稱,返回是否存在:boolean ' sheet_exists("工作表2") Dim st As Object On Error Resume Next Set st = ActiveWorkbook.Sheets(sheet_name) If Err.Number = 0 Then ' 如果沒有報錯,返回truesheet_exists = True Elsesheet_exists = False End If

workbook_is_open:工作表是否存在

Function workbook_is_open(wb_name As Variant) As Boolean ' 傳入工作簿名稱,返回是否打開:boolean ' sheet_exists("工作表2") Dim st As Object On Error Resume Next Set st = Workbooks(wb_name) If Err.Number = 0 Then ' 如果沒有報錯,返回trueworkbook_is_open = True Elseworkbook_is_open = False End If

text_join:split的反函數(shù)

該函數(shù)在Excel2019版已經(jīng)引入,早期的版本可以通過自定義函數(shù)實現(xiàn)

Function text_join(sep As String, is_skip_blank As Boolean, ParamArray ranges() As Variant) ' sep:分隔符,is_skip_blank:是否跳過空值,ranges:數(shù)組 Dim rngs, sub_rng As Variant Dim s As String s = "" For Each rngs In rangesFor Each sub_rng In rngsIf is_skip_blank = True Then ' 是否跳過空格If Len(sub_rng) > 0 Thens = s & sep & RngEnd IfElses = s & sep & RngEnd IfNext Next text_join = Replace(s, sep, "", 1, 1) ' 把開頭的分隔符去掉 End Function

ifs:多判斷

該函數(shù)在excel2019版本后才有,早期的版本可以在vba中定制;無須重復if嵌套

Function udf_ifs(ParamArray args() As Variant) Dim i As Byte Dim args_len As Byteargs_len = UBound(args) ' 參數(shù)索引下標從0開始 If args_len < 1 Then Exit FunctionFor i = 0 To UBound(args) Step 2If args(i) = True Thenudf_ifs = args(i + 1) ' 如果參數(shù)是true,返回后面一個參數(shù)值Exit FunctionEnd If Next' 如果都沒有是,參數(shù)個數(shù)是基數(shù),返回最后一個參數(shù) If args_len Mod 2 = 0 Then udf_ifs = args(args_len): Exit Functionudf_ifs = "#N/A" ' 參數(shù)是偶數(shù),且沒有true對象,返回錯誤值 End Function

range_workbook_name:返回單元格所在的工作簿名稱

返回單元格所在工作簿的名稱,parent表示父對象,比如單元格的父對象是工作表,工作表的父對象是工作簿,這里調(diào)用了兩次

Function range_workbook_name(rng As Variant) As String range_workbook_name = rng.Parent.Parent.Name End Function

text_speak:說出文本

使用的是Excel的文本轉(zhuǎn)化成語音的轉(zhuǎn)化生成器,講述傳入的字符串

Function text_speak(text) ' Application.Speech.Speak ("hello alice") Application.Speech.Speak (text) text_speak = text End Function

is_like:模式匹配

使用vba的like函數(shù),類似于sql中的like,like中pattern參數(shù)的字符

pattern字符解釋
任意單個字符
*0個或多個字符
#任意單個數(shù)字(0-9)
[charlist]字符列表中的任意單個字符
[!charlist]不在字符列表中的任意單個字符
Function is_like(str As String, pattern As String) As Boolean is_like = str Like pat End Function

總結(jié)

以上是生活随笔為你收集整理的VBA函数定义及说明的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。