我希望能够解析工作表并根据其中一个单元格中的“已注销”条件删除某些行。诀窍是,它不能是它的每个实例,只是下一行显示'status'数组的一个参数的实例。工作表的大致大小为4列,大约为10000行。
Dim firstRow As Long
Dim nextRow As Long
Dim currentDate(1 To 5) As String
Dim totalDelete As Long
Dim p As Integer
Dim i As Integer
Dim status(1 To 5) As String
status(1) = "Available"
status(2) = "Email"
status(3) = "Available, No ACD"
status(4) = "Aux, Technical Issues"
status(5) = "Aux, Client Callback"
currentDate(1) = Sheets("Cover").Range("E12")
currentDate(2) = Sheets("Cover").Range("F12")
currentDate(3) = Sheets("Cover").Range("G12")
currentDate(4) = Sheets("Cover").Range("H12")
currentDate(5) = Sheets("Cover").Range("I12")
firstRow = 2
nextRow = 3
totalDelete = 0
For i = 1 To 5
For p = 1 To 5
Do While firstRow <= 10000
If Cells(firstRow, "C") = "Logged Off" And Cells(nextRow, "C") = status(p) And Cells(nextRow, "B") = currentDate(i) Then
Rows(firstRow).Delete
totalDelete = totalDelete + 1
Else
firstRow = firstRow + 1
nextRow = nextRow + 1
End If
Loop
Debug.Print currentDate(p)
Debug.Print status(p)
Next p
Next i
Debug.Print totalDelete
现在我期待的是它循环大约10000行并检查我上面描述的内容。它通过几个循环来检查我所拥有的两个数组中的所有可能的日期和状态。代码中的调试只是我检查状态和currentDate是否正确输出,它们是。这让我相信我的IF声明可能有些问题。但是,我不是最熟练的,所以我只是没有看到我出错的地方。
A | B | C | D
1 data | 3/25/2019 | Logged Off | data
2 data | 3/25/2019 | Logged Off | data
3 data | 3/25/2019 | email | data
4 data | 3/25/2019 | email | data
所以在运行代码之后,我希望它至少可以删除第2行。
您的代码中存在一些问题。
1)当您计划删除循环中的行时,请向后工作。
想象一下,你击中行3
,你必须删除它(firstRow = 3
)。你删除它,现在行4
是行3
,你迭代firstRow
到4
。基本上WAS行4
(现在是Row 3
)的行被跳过并且不被检查。
代替
FirstRow = 10000
Do While firstRow >= 2
并在每个循环中减少firstrow
:
firstRow = firstRow - 1
确保你不要从地下拉出地毯。这可能会或可能不会解决您所看到的问题,但这是您代码中的明确错误。
2)循环中的循环
这是5 x 5 x 10000
循环或250000
循环。这非常具有侵略性。相反,只需循环10000次并测试如下:
If Cells(firstRow, "C") = "Logged Off" And inStr(1, Join(status, "|"), Cells(firstRow+ 1, "C").value, 1) And InStr(1, Join(currentDate, "|"), Cells(firstRow + 1, "B"), 1) Then
您可以使用Join()
函数将数组转换为每个元素之间由|
分隔的单个字符串。 Instr()
然后测试你的单元格值是否为字符串。我们将Instr()
的最后一个参数设置为1
,以便它不区分大小写。 10000循环会快得多。
3)你不需要nextRow
变量(虽然这只是挑剔,所以你可以忽略,如果你嫁给那个东西。)
而是使用Cell(firstRow + 1,“C”)或Cells(firstRow,“C”)。Offset(,1)来进行检查。减少增量和跟踪这种方式的变量。
这是重写:
Dim firstRow As Long
Dim currentDate(1 To 5) As String
Dim totalDelete As Long
Dim status(1 To 5) As String
status(1) = "Available"
status(2) = "Email"
status(3) = "Available, No ACD"
status(4) = "Aux, Technical Issues"
status(5) = "Aux, Client Callback"
currentDate(1) = Sheets("Cover").Range("E12")
currentDate(2) = Sheets("Cover").Range("F12")
currentDate(3) = Sheets("Cover").Range("G12")
currentDate(4) = Sheets("Cover").Range("H12")
currentDate(5) = Sheets("Cover").Range("I12")
firstRow = 10000
totalDelete = 0
Do While firstRow >= 2
If Cells(firstRow, "C") = "Logged Off" And inStr(1, Join(status, "|"), Cells(firstRow+ 1, "C").value, 1) And InStr(1, Join(currentDate, "|"), Cells(firstRow + 1, "B"), 1) Then
Rows(firstRow).Delete
totalDelete = totalDelete + 1
End If
firstRow = firstRow - 1
Loop
Debug.Print totalDelete