一、vbaInStr函數用法
vbaInStr函數是VBA字符串函數之一,主要是用於查找一個字符串中是否包含另外一個字符串,並返回查找到的第一個子串出現的位置。他有如下幾個參數:
'vbainstr(string1,string2,[compare]) string1: 要查找的字符串。 string2: 要查找的子串。 compare: 可選參數,指定vbaInStr函數的查找方式,默認是0,表示區分大小寫。當compare為1時表示不區分大小寫。
返回值:如果string2子串在string1中找到,則返回string2在string1中第一次出現的位置,如果沒有找到則返回0。
二、VBA函數介紹
VBA函數的作用是為了簡化代碼,方便代碼編寫和重用。在VBA中,函數與子程序的不同之處在於:函數返回一個值,而子程序不返回任何值。
三、vbaDir函數
vbaDir函數返回一個目錄中符合某種文件名匹配模式的文件名。
'vbaDir(Path,[Attributes]) Path: 一個字符串,包含要查詢的文件名或者路徑。 Attributes: 可選參數,指定文件或文件夾的屬性。可以為以下值之一: - vbNormal:(默認) 普通文件 - vbReadOnly: 只讀文件 - vbHidden: 隱藏文件 - vbDirectory: 目錄文件,可與上面三個選項同時使用。
四、vbArray函數
vbArray函數可以用於確定一個變量是否為數組。如果一個變量是數組,則返回True,否則返回False。
Dim arr() As Integer Dim num As Integer Debug.Print VarType(arr) = vbArray 'True Debug.Print VarType(num) = vbArray 'False
五、VBA函數查詢
VBA自帶了很多函數,但並不是所有的函數都能滿足我們的需要。當我們遇到無法實現的功能時,我們可以考慮使用VBA函數庫。
可以在VBE中打開「工具->引用」菜單,勾選Microsoft Excel Object Library以及Microsoft Scripting Runtime,再在VBE中打開「視圖->對象瀏覽器」,即可看到VBA函數庫。
六、vbInt函數
vbInt函數可以取整。函數的返回值為double類型,表示取整後的值。
Dim a As Double a = 4.5 Debug.Print Int(a) '4 Debug.Print Round(a) '5 Debug.Print Round(a, 0) '5
七、vbaCount函數
vbaCount函數可以統計數組中元素的數量。
Dim arr() As Integer ReDim arr(0 To 5) Debug.Print UBound(arr) - LBound(arr) + 1 '6
八、if Instr函數
If Instr函數可以判斷一個字符串是否包含某個子串。當包含子串時,返回子串在字符串中的位置;否則返回0。
Dim str As String str = "Hello World!" If InStr(str, "World") Then Debug.Print "包含World!" Else Debug.Print "不包含World!" End If
九、Instr函數實例
Instr函數可以用於很多場景,以下是一些常見的實例:
1、查找字符串中數字的位置:
Function FindNumberInStr(str As String) As Integer Dim i As Integer For i = 1 To Len(str) If InStr("0123456789", Mid(str, i, 1)) Then FindNumberInStr = i Exit Function End If Next i End Function
2、查找字符串中最後一個數字的位置:
Function FindLastNumberInStr(str As String) As Integer Dim i As Integer For i = Len(str) To 1 Step -1 If InStr("0123456789", Mid(str, i, 1)) Then FindLastNumberInStr = i Exit Function End If Next i End Function
3、查找字符串中第一個空格的位置:
Function FindSpaceInStr(str As String) As Integer FindSpaceInStr = InStr(str, " ") End Function
4、查找字符串中第二個空格之後的子串:
Function FindSecondSpaceInStr(str As String) As String Dim i As Integer Dim cnt As Integer Dim lenstr As Integer lenstr = Len(str) For i = 1 To lenstr If Mid(str, i, 1) = " " Then cnt = cnt + 1 If cnt = 2 Then FindSecondSpaceInStr = Mid(str, i + 1, lenstr - i) Exit Function End If End If Next i End Function
原創文章,作者:SKESZ,如若轉載,請註明出處:https://www.506064.com/zh-hk/n/332129.html