如果单元格包含某个字符串,则VBA会从电子表格中删除行

时间:2016-11-24 16:22:04

标签: vba excel-vba object excel

我对VBA很新。我试图在电子表格中隔离特定的客户交易。

列“A”包含客户付款方式(预付款或其他各种方法)。列“D”包含我们正在发货的客户,列“L”包含我们发货的客户。

如果“A”栏中的单元格有'预付',我想在列“D”中搜索客户名称(jaba)。然后,我将删除所有不包含此客户的行。如果列“A”中的单元格不是“预付”,我希望它在列“L”中搜索客户名称,并删除所有不包含该字符串的行。当我运行下面提供的代码时,我在以下脚本上得到1004错误'如果cell3.Find(ContainWord)是Nothing Then'。任何帮助将不胜感激。

Sub DoNotContainClearCells()
Dim rng As Range
Dim rng2 As Range
Dim rng3 As Range

Dim cell As Range
Dim cell2 As Range
Dim cell3 As Range
Dim ContainWord As String

'What range do you want to search?
  Set rng = Range("A:A")
  Set rng2 = Range("D:D")
  Set rng3 = Range("L:L")
  'What phrase do you want to test for?
  ContainWord = "jaba"

For Each cell In rng

    If cell.Value = "prepaid" Then


        'Loop through each cell in range and test cell contents
        For Each cell2 In rng2.Cells
            If cell2.Find(ContainWord) Is Nothing Then EntireRow.Delete
        Next cell2

        Else
        'Loop through each cell in range and test cell contents
        For Each cell3 In rng3.Cells
            If cell3.Find(ContainWord) Is Nothing Then EntireRow.Delete
        Next cell3

    End If
Next
End Sub

1 个答案:

答案 0 :(得分:0)

如果不讨论代码的逻辑,这不是问题的一部分,我可以告诉你

  

运行时错误' 1004':需要对象

在这一行:

If cell3.Find(ContainWord) Is Nothing Then EntireRow.Delete

是因为EntireRow.Delete缺少范围(请参阅Range.EntireRow Property (Excel)

解决方案:替换以下行:

If cell2.Find(ContainWord) Is Nothing Then EntireRow.Delete
If cell3.Find(ContainWord) Is Nothing Then EntireRow.Delete

用这些:

If cell2.Find(ContainWord) Is Nothing Then cell2.EntireRow.Delete
If cell3.Find(ContainWord) Is Nothing Then cell3.EntireRow.Delete

建议始终位于modules \ classes \ userforms:

的顶部
Option Explicit

这会在编译时间之前给出Compile error: Variable not defined突出显示错误(参见Option Explicit Statement