代码1:
Sub charlsezhang1()
arr1 = Array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
arr2 = [{1,3,5,7,9}]
'想得到一个减去的数组
For Each i In arr1
For Each j In arr2
If i = j Then
arr1(i) = ""
End If
Next
Next
For Each i In arr1
Debug.Print i
Next
End Sub
结果是达到了,就是有点傻
代码2: 还是只把要删除的元素置空,但是不同写法有不同的问题
- 如果用for i = lbound() to ubound() ,可以置空某元素
- 如果用 for each i in array,置空i 不能改变数组里的元素
- 如果用 for each i in array,需要用match反查i的index,然后用array(i) 的方式置空
- match反查的局限性:1只能查重复元素的第1个index, 2需要把查找内容加引号"",3 match作为工作表函数,index默认从1开始,即使array本身index从0开始!
Sub demaxiya1()
Dim str1
str1 = "a,aa,bb,cc,e,f,Aa,5,100,66,999"
arr1 = Split(str1, ",")
Debug.Print Join(arr1)
Debug.Print
For i = LBound(arr1) To UBound(arr1)
If arr1(i) = "999" Then '写成i=999或 i="999",都能找到
arr1(i) = ""
End If
Next
Debug.Print Join(arr1)
Debug.Print
For Each i In arr1
If i = "66" Then
Debug.Print "找到66" '写成i=66或 i="66",都能找到,证明两种写法无差别?
i = ""
End If
Next
Debug.Print Join(arr1)
Debug.Print
Debug.Print Application.Match("100", arr1, 0)
'match是vba函数,返回index与VBA代码的array不对应,index从1开始
'arr1的每个内容都是字符串?NO
'是match语法要求这么写,写10,而不"10"会无法查到
x1 = Application.Match("100", arr1, 0)
Debug.Print x1
arr1(x1 - 1) = ""
Debug.Print Join(arr1)
Debug.Print
arr1(Application.Match("5", arr1, 0) - 1) = ""
Debug.Print Join(arr1)
Debug.Print
End Sub