以下是我为使工作中的某些流程自动化而生成的一些代码的摘录。我生成的宏的一个元素是删除报告范围之外的所有等级。由于范围外的等级总是在变化,但是范围内的等级已设置,因此我决定尝试使用数组。我以前从未使用过这些,而且我在网上找到了一些代码可以用作模板,问题是该代码似乎将所有成绩标记为“ false”,无论它们是否在数组中。我已通过将delete更改为设置内部颜色来检查范围和列,这确认列和范围是正确的。我认为问题是我没有将功能与子代码正确链接。任何建议将不胜感激:
Sub SortData()
Dim firstrow As Long
Dim LastRow As Integer
Dim arrGrades As Variant, grd As Variant
arrGrades = Array("Range B", "Range C", "Range D Experienced", "Range D", "Range E", "Range E2", "SCS 1", "SCS 2", "SCS 3", "Student")
With Sheets("Active OoD")
.Select
firstrow = .UsedRange.Cells(1).Row
LastRow = .UsedRange.Rows(.UsedRange.Rows.Count).Row
Set rng = Range("H2", "H" & LastRow)
With rng
For i = .Rows.Count To 1 Step -1
If IsInArray(.Item(i), arrGrades) = False Then
.EntireRow.Delete
End If
Next i
End With
End With
End Sub
Function colNumeric(ColAlpha As String)
ColAlpha = UCase(ColAlpha)
If Len(ColAlpha) = 3 Then
Col_no = (Asc(Left(ColAlpha, 1)) - 64) * 26 * 26 + _
((Asc(Mid(ColAlpha, 2, 1)) - 64) - 1) * 26 + _
Asc(Right(ColAlpha, 1)) - 64
ElseIf Len(ColAlpha) = 2 Then
Col_no = (Asc(Left(ColAlpha, 1)) - 64) * 26 + _
(Asc(Right(ColAlpha, 1)) - 64)
Else
Col_no = Asc(Right(ColAlpha, 1)) - 64
End If
End Function
Function IsInArray(valToBeFound As Variant, arr As Variant) As Boolean
'Function IsInArray(grd As Variant, arrGrades As Variant) As Boolean
'INPUT: Pass the function a value to search for and an array of values of any data type.
'OUTPUT: True if is in array, false otherwise
Dim element As Variant
On Error GoTo IsInArrayError: 'array is empty
For Each element In arr
If element = valToBeFound Then
IsInArray = True
Exit Function
End If
Next element
Exit Function
IsInArrayError:
On Error GoTo 0
IsInArray = False
End Function
答案 0 :(得分:3)
此行...
.EntireRow.Delete
...指的是 整个范围 的整行。因此,例如,如果Rng
指向范围H2:H10
,则EntireRow
指向$2:$10
,因此所有内容都将被删除。相反,请尝试按以下方式引用当前行...
.Item(i).EntireRow.Delete