VBA - 删除不同工作表之间的名称

问题描述 投票:0回答:1

在 Sheet2 中,单元格区域 B4:B15 中有名称。如果在单元格 E4:E200 中找到完全相同的名称,我需要从 Sheet1 中删除它们。如果可能的话,删除找到名称的整行也会很好。不知道如何开始。

excel vba cell between
1个回答
-1
投票

当您删除行时,您需要以相反的顺序运行迭代循环,因为删除行将导致宏跳过正在应用的逻辑的行。

这是一个非常基本的示例,我查看两个不同的范围,并检查第一个范围中的任何名称是否存在于第二个范围中,以删除第二个范围的该行。

for 循环中发生的事情是首先迭代列表并获取名称并检查另一个列表以查看它是否具有该名称,然后对下一个名称执行此操作,依此类推。

Sub deletelist()
Dim i As Long, x As Long
Dim LastRow As Long, Lastrow2 As Long
Dim sh1 As Worksheet, sh2 As Worksheet
Dim wb As Workbook

Set wb = ThisWorkbook
'Change this range for the sheet that has the list of names
Set sh1 = wb.Sheets("Sheet1")
'Change this to the sheet that has the list of names to be deleted
Set sh2 = wb.Sheets("Sheet2")


LastRow = wb.sh1.Cells(Cells.Rows.Count, "A").End(xlUp).Row


Lastrow2 = wb.sh2.Cells(Cells.Rows.Count, "F").End(xlUp).Row

' change where it says "To 1" to be where the first data exists, if it starts on row 2, put 2.
For i = LastRow To 1 Step -1
    For x = Lastrow2 To 1 Step -1
        ' where it says cells(i,1), i denotes the row, 1 is the column to check, change accordingly
        If wb.sh1.Cells(i, 1).Value = wb.sh2.Cells(x, 6).Value Then
            wb.sh2.Cells(x, 6).EntireRow.Delete
        End If
    Next x
Next i
        
End Sub
© www.soinside.com 2019 - 2024. All rights reserved.