繁体   English   中英

如果列中的行范围与另一工作表中的列的范围相匹配,则 VBA 会清除行中单元格的内容

[英]VBA clear contents from cells in row if range of rows in column match range from column in another sheet

我想我很接近,但我不知道如何解决这个问题。 一切看起来都不错。 我有数据 sht1 列“T2”和“MO123”,它匹配 Sht2 上 B 列中的第 1 行,不确定它是否抱怨 .ClearContent 或我的范围。 谢谢你能给我的任何帮助。 我会添加代码以防万一您想尝试一下。 -保罗

Sub Delete_Picklist_Rec()
    Dim Sht1 As Worksheet, Sht2 As Worksheet
    Dim LstRw As Long, lookup_rng As Range, x


    Set Sht1 = Sheets("Pick Ticket Schedule")
    Set Sht2 = Sheets("Pick Ticket (History)")
    Set lookup_rng = Sht2.Range("B2:B7")

    With Sht1
        LstRw = .Cells(.Rows.Count, "T").End(xlUp).Row
        MsgBox "LstRw:" & LstRw
        For x = LstRw To 1 Step -1
            If .Cells(x, 1) = lookup_rng Then
                Range("J" & x & ":K" & x).ClearContents Shift:=xlUp 'Need to delete value in cell J & K for the row that matches
            End If
        Next x

    End With

End Sub

在此处输入图片说明

为了有一个答案,所以每个人都知道它已经解决了:

第一个问题是Shift:=xlUp不是一个参数ClearContents (它没有参数),以便消除,允许明确的工作。 或者,您可以使用.Delete代替,然后使用Shift参数。

其次,您没有为Range指定工作表,因此默认情况下它使用Active Sheet

第三,您将单个单元格值与需要通过 find 命令或循环完成的范围进行比较。 我使用了Find命令,因为它通常是解决此类问题的最快解决方案。 它还具有比我使用的更多的参数,因此如果需要,您可以将它们添加到其中。 在此处查看有关 find 命令的更多信息

这是基于我所说的解决方案:

Sub Delete_Picklist_Rec()
    Dim Sht1 As Worksheet, Sht2 As Worksheet
    Dim LstRw As Long, lookup_rng As Range, x As Long


    Set Sht1 = Sheets("Pick Ticket Schedule")
    Set Sht2 = Sheets("Pick Ticket (History)")
    Set lookup_rng = Sht2.Range("B2:B7")

    With Sht1
        LstRw = .Cells(.Rows.Count, "T").End(xlUp).Row
        MsgBox "LstRw:" & LstRw
        For x = LstRw To 1 Step -1 'Doesn't need to loop backwards if just clearing but does if using Delete.
            If Not lookup_rng.Find(what:=.Cells(x,1), LookIn:=xlValues, lookat:=xlWhole) Is Nothing Then
                .Range("J" & x & ":K" & x).ClearContents 'Or .Delete Shift:=xlUp
            End If
        Next x

    End With

End Sub

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM