VBA,关于filter()函数的局限性和原理,自己写了一个仿造filter同功能自定义函数

1 filter() 函数的局限性

  • filter() 非精确查找,是模糊查询,类似于 like 的功能
  • Filter函数可以区分" " 即1个空格,但不能区分""空值或空白。--为什么,因为filter的原理类 if like
Sub test110()
'Filter函数可以区分" " 即1个空格,但不能区分""空值或空白。
'filter() 非精确查找
'filter() 的原理是? if  like ?

arr1 = Array(1, "", "", 2, 3, " ", "   ", 4, 5, 55, "", 15, "汉字", 95)
arr2 = Filter(arr1, 5, True)
arr3 = Filter(arr1, 5, False)
arr4 = Filter(arr1, "", True)
arr5 = Filter(arr1, " ", True)

display_array (arr1)
display_array (arr2)
display_array (arr3)
display_array (arr4)
display_array (arr5)


End Sub


Function display_array(x)    '可显示1维数组

For Each I In x
   Debug.Print I;
Next
Debug.Print

For Each I In x
   Debug.Print I & ",";
Next
Debug.Print
Debug.Print

End Function

2 filter() 的原理是类 if  like 

  • 为什么呢,这个跟VBA的filter() 函数的实现原理相关
  • 这是活跃的EXCEL大神 香川群子写的,我学习下,真实很佩服这些大神对VBA的深刻理解
  • http://www.excelpx.com/thread-376056-1-1.html

2.1 我自己写了一个类 filter()  功能的自定义函数 copy_filter()

脚手架版本

Sub test111()

arr1 = Array(1, 2, 3, 4, 5, 13, 33)
Call copy_filter(arr1)




End Sub



Function copy_filter(x)
Dim arr2()
ReDim arr2(LBound(x) To UBound(x))

m = 0
For I = LBound(x) To UBound(x)
      Debug.Print "x" & "(" & I & ")=" & x(I);
      Debug.Print "  ";
      If x(I) Like "*3*" Then
     arr2(m) = x(I)

      Debug.Print "arr2" & "(" & m & ")=" & arr2(m)
      m = m + 1
    Else
      Debug.Print "没找到?"
    End If
Next



'copy_filter = y


'For Each J In y
'   Debug.Print J;
'Next



End Function

2.2 精简版自定义函数   copy_filter()  实现了 filter()的功能

Sub test111()
arr1 = Array(1, 2, 3, 4, 5, 13, 33)
display_array (copy_filter(arr1, 3))
End Sub



Function copy_filter(x, a)         '这个函数实现了筛选功能
Dim arr2()
ReDim arr2(LBound(x) To UBound(x))
m = 0
For I = LBound(x) To UBound(x)
    If x(I) Like "*" & a & "*" Then
       arr2(m) = x(I)

       m = m + 1
    End If
Next
copy_filter = arr2()
End Function



Function display_array(x)    '可显示1维数组,这个函数实现了显示数组功能
For Each I In x
   Debug.Print I & ",";
Next
Debug.Print
Debug.Print
End Function

发布了370 篇原创文章 · 获赞 45 · 访问量 9万+

猜你喜欢

转载自blog.csdn.net/xuemanqianshan/article/details/103976751
今日推荐