1 VBA里可以使用的3类函数,都是独立的
- VBA函数
- application函数
- application.worksheetfunction函数
- VBA函数,appliacation函数,工作表函数,三种同名函数完全独立
- EXCEL工作表函数(默认都是只能针对一个cell做作用的! 并且一般是cell.value)
1.1 比如 match函数
- vba.match ?好像是没有
- application.match() '运行时如果查不到,会返回错误值
- application.worksheetfunction.match() '运行时如果查不到会直接报错跳出
Sub test1()
Dim dict1 As New Dictionary
Dim dict2 As Object
Set dict2 = CreateObject("scripting.dictionary")
arr1 = Array(1, 2, 3, 4, 5)
arr2 = [{11,22,33,44,55}] '下标默认从1开始,因为是EXCEL格式
For i = LBound(arr1) To UBound(arr1)
dict1(arr1(i)) = arr2(i + 1)
Next
For Each i In dict1.Keys()
Debug.Print i & "," & dict1(i)
Next
target1 = 55
Debug.Print dict1.Keys(Application.Match(target1, dict1.Items, 0) - 1)
Debug.Print dict1.Keys(WorksheetFunction.Match(target1, dict1.Items, 0) - 1)
'Debug.Print dict1.Keys(Match(target1, dict1.Items, 0) - 1) '没这个VBA函数
End Sub
1.2 比如 trim函数
trim() 是不是可以不只针对一个cell? 多个?可以针对字符串中间的空格不处理
- trim() ' 只处理首位的空格
- application.trim() '处理首位的空格,中间的空格也会被缩为1个
- application.worksheetfunction.trim() '处理首位的空格,中间的空格也会被缩为1个
Sub test1()
str1 = " a b c d e "
Debug.Print "str1="; str1
Debug.Print "Trim(str1)=" & Trim(str1)
Debug.Print "Application.Trim(str1)=" & Application.Trim(str1)
Debug.Print "Application.WorksheetFunction.Trim(str1)=" & Application.WorksheetFunction.Trim(str1)
End Sub
1.3 比如replace函数(VBA函数和 worksheetfunction 的replace语法完全不同)
- replace() / VBA.Replace(目标我在你这字符串, "替换后的新文本", "要被替换的文本")
- worksheetfunction.replace() / Application.worksheetfunction.replace()
- worksheetfunction.Replace(old_text,start_num,num_chars,new_text)
- worksheetfunction.replace(目标完整字符串,开始位置,从开始位置开始的替换个数,新的文本)
Sub test1()
str1 = "hello,xxx,xxx,xxx"
Debug.Print str1
Debug.Print Replace(str1, "xxx", "yyy")
Debug.Print Application.Replace(str1, 7, 3, "y")
Debug.Print WorksheetFunction.Replace(str1, 11, 2, "yy")
End Sub
1.4 VBA.iserror() 函数 和 application.iferror() 函数
Sub test100()
Debug.Print Application.Match(3, Array(1, 3, 5), 0)
Debug.Print IsError(Application.Match(3, Array(1, 3, 5), 0))
Debug.Print Application.Match(2, Array(1, 3, 5), 0)
Debug.Print IsError(Application.Match(2, Array(1, 3, 5), 0))
Debug.Print
Debug.Print Application.IfError(Application.Match(3, Array(1, 3, 5), 0), "999")
Debug.Print Application.IfError(Application.Match(2, Array(1, 3, 5), 0), "888")
Debug.Print
End Sub