The main problem is that it is troublesome to delete a line when looping, because after deleting a line, the loop still directly accesses the next line, which will cause certain exceptions .
Article directory
Select a column and delete the specified row
The following code is a safe way to delete a specified row by selecting a column :
Columns("G:G").Select '选择一列
i = 1 '定义一个循环变量,来控制参与循环的元素
While (IsEmpty(Selection(i)) = False) '用是否遇到空单元格来判断是否遍历完成
If (InStr(1, Selection(i), "特定条件", 0) > 0) Then
nowRow = Selection(i).Row '获得当前行号
Rows(nowRow).Delete '删掉当前行
i = i - 1 '抵消删除对循环的影响
End If
i = i + 1 '循环中循环变量正常地加1
Wend
remove an element from the array
However, deleting an element in an array is inconvenient to do so. Because VBA does not seem to provide 数组.delete(index)
such a useful function.
Method 1: Using dynamic arrays, conditional judgment deletion in the loop
However, it can be combined with dynamic arrays to assign the array of deleted elements to a new array, as shown in the following code . The array in it b
is the new array after deleting elements:
arr1 = Array(1, "特定条件", 3, 999, 1, "特定条件", 3) '定义一个数组
Dim b() As String '定义新数组
k = 0 '记录新数组的长度
For i = 0 To UBound(arr1) '用数组长度来判断是否遍历完成
If (InStr(1, arr1(i), "特定条件", 0) <= 0) Then
ReDim Preserve b(0 To k) '添加到新数组
b(k) = arr1(i)
k = k + 1
End If
Next
'结果是b = Array(1, 3, 999, 1, 3)
Reference: How to remove the null value in the array in vba-Baidu Know-jmeycn
Note that
UBound
getting the length of the array is used instead ofLen
. In VBA,Len
it is used to obtain the length of Expression, such as the length of a string;UBound
return the maximum subscript of the specified array.
Note 2: When the length of the array is 0,UBound
the "subscript out of bounds" error will occur if the length is obtained. So here k is used as the length value of the new array.
Method 2: Delete the specified value in the array
Of course, if you want to delete the specified value in the array , the more concise way is to use it Filter
, as follows:
arr1 = Array(1, "特定条件", 3, 999, 1, "特定条件", 3) '定义一个数组
b = Filter(arr1, "特定条件", False)
'结果也是b = Array(1, 3, 999, 1, 3)
Summary: Method 1 is recommended
Obviously, method 1 is more general, and other information other than the array can be used as a conditional judgment.
The deletion result is shown in the figure below: