我正在尝试使用vba从excel中删除重复的行。该函数检查列中的值,如果找到该值,则删除该行。我编写了以下代码,它可以工作但是备用行被删除了。一个被删除,一个没有。匹配在每次迭代中找到。我错了吗?
Private Function DeletePreviousRecords(Program As String, targetSheet As String) As Boolean
Dim lastRow As Long, iCTR As Integer: iCTR = 2
Dim IsDone As Boolean
lastRow = GetLastRow(targetSheet)
Do
If Sheets(targetSheet).range("G" & CStr(iCTR)) = Program Then
MsgBox "Found Match at Row -" & CStr(iCTR)
Sheets(targetSheet).Rows(iCTR).Delete
IsDone = True
End If
iCTR = iCTR + 1
Loop While iCTR < lastRow
DeletePreviousRecords = IsDone
End Function
Private Function GetLastRow(sheetName As String) As Long
Dim lastRow As Long
'ActiveWorkbook.Sheets(targetSheet).Cells(Sheets(targetSheet).Rows.Count, "C").End(xlUp).Row
With ActiveWorkbook.Sheets(sheetName)
lastRow = .Cells(Sheets(sheetName).Rows.Count, "C").End(xlUp).Row
End With
GetLastRow = lastRow + 1
End Function
答案 0 :(得分:1)
删除行时,您必须意识到您正在删除与您循环的相同行。我的建议是从LAST行开始并使用-1循环计数器进行迭代。这样,您可以安全地删除行而不会影响剩余的行。换句话说 - 从lastRow向后迭代到2(或者你的起始行是什么)。