我有以下源 csv (wbSource):
身份证号码 | 价值 |
---|---|
125 | A |
145 | A |
173 | A |
201 | A |
203 | A |
650 | B |
888 | B |
我想使用 VBA 将 Value = A 的所有行复制到另一个工作簿(“Target.xlsb”)中的表“Principal”,但可能已存在的任何行除外。由于多种原因,目标表中的行无法更改,主要是因为它们可能包含源 csv 中不存在的新信息。
为了完成此任务,我有一个函数来检查 Primary 表中是否已存在 Value = A 的 ID。如果是,循环将删除源 csv 中的行。
目标是,运行此函数后,我将按“A”值过滤源 csv,并将所有可见行复制到目标表中。
但是,通过这样做,它会在接下来的迭代中跳过一行。 这是我创建的函数(在 IA 的帮助下),如果不是每次删除行时都会跳过行,它可以完美运行。
Function CheckAndDeleteRows() As String
Dim wbSource As Workbook
Dim wbTarget As Workbook
Dim wsSource As Worksheet
Dim tblPrincipal As ListObject
Dim rngSource As Range
Dim rngPrincipal As Range
Dim cell As Range
Dim found As Range
' Open the workbooks
Set wbSource = Workbooks("Source.csv")
Set wbTarget = Workbooks("Target.xlsb")
' Set the worksheet in Source workbook and the table in Target workbook
Set wsSource = wbSource.Sheets(1)
Set tblPrincipal = wbTarget.Sheets(1).ListObjects("Principal")
' Set the ranges to check
Set rngSource = wsSource.Range("B2:B" & wsSource.Cells(wsSource.Rows.Count, "B").End(xlUp).Row)
Set rngPrincipal = tblPrincipal.DataBodyRange.Columns(1)
' Loop through each cell in column B of Source workbook
For Each cell In rngSource
If cell.Value = "A" Then
' Check if the value is in the Principal table of Target workbook
Set found = rngPrincipal.Find(cell.EntireRow.Value, LookIn:=xlValues, LookAt:=xlWhole)
If Not found Is Nothing Then
' Delete the row in Source workbook
cell.EntireRow.Delete
' THIS IS WHERE I'D LIKE TO DECREASE THE COUNTER BY ONE'
End If
End If
Next cell
End Function
最佳解决方案是能够减少 cell.EntireRow.Delete 之后的计数器,类似于 cell = cell - 1,但此方法不允许这样做。
是否有其他方法可以在每次循环删除源 csv 中的一行时将“对于每个单元格”计数器减 1?
For Each
更改为 For
循环cell.EntireRow.Value
:EntireRow
没用 Dim lastRow As Long, iRow As Long
lastRow = wsSource.Cells(wsSource.Rows.Count, "B").End(xlUp).Row
For iRow = lastRow To 2 Step -1
Set cell = wsSource.Cells(iRow, "B")
If cell.Value = "A" Then
Set found = rngPrincipal.Find(cell.Value, LookIn:=xlValues, LookAt:=xlWhole)
If Not found Is Nothing Then
cell.EntireRow.Delete
End If
End If
Next cell