通过使用vba检查相邻列值来删除整行

时间:2016-12-03 17:04:09

标签: excel vba excel-vba macros

我在B列中有一个包含字符串的工作表,大约有500行,我的单元格空白/填充了A列和C列中的值到M。

我写了一个宏,它将获取B列中每行的字符串值,如果该行的相邻单元格(从C列到M列)为空,则它将删除整行。但即使相邻单元格中的任何一个具有值,它也会跳过该行。

这是我的表格看起来像

 A      B           C   D   E   F   G   H   I   J   K   L   M
1.2   SERVER_P             RE1                         GR5 
7.3   PROXY NET
4.5   NET CON V1                        GR

预计它应该删除整个2行,因为库存C到M是空的。我上面给出了三行,但是我的工作表包含大约500行数据。

这是我现在拥有的

Dim rcount As Long, ccount As Long
Dim Count As Long, Lastrow As Long
Dim Targetname As String, Deletedname As String
Dim objFSObject As Object

Set objFSObject = CreateObject("Scripting.FileSystemObject")

Count = 0
Sheets("Sheet2").Activate

With ActiveSheet
    'count the rows till which strings are there
    Lastrow = .Cells(.Rows.Count, "B").End(xlUp).Row
End With

For rcount = 1 To Lastrow
    Targetname = Cells(rcount, 2).Value
    Count = 0                     'reset the counter 
    Cells(rcount, 2).Select
    For ccount = 1 To 11
        Deletedname = ActiveCell.Offset(0, ccount).Value
        If Len(Trim$(Deletedname)) > 0 Then
            ccount = 11
        Else
            Count = Count + 1
            If Count = 11 Then
                Rows(rcount).EntireRow.Delete
            End If
        End If
    Next ccount
Next rcount

但是我的宏删除了许多符合条件的行,即C到M是空的,但是仍然没有删除很少的行,它们的单元格也从列C到M为空。

有人可以帮我解决这个问题。

1 个答案:

答案 0 :(得分:0)

借助上面的@Logan Reed评论

  Dim rcount As Long, ccount As Long
  Dim Count As Long, Lastrow As Long
  Dim Targetname As String, Deletedname As String
  Dim objFSObject As Object

  Set objFSObject = CreateObject("Scripting.FileSystemObject")

  Count = 0
  Sheets("Sheet2").Activate

  With ActiveSheet
     'count the rows till which strings are there
     Lastrow = .Cells(.Rows.Count, "B").End(xlUp).Row
  End With

  For rcount = Lastrow to 1 Step -1
    Targetname = Cells(rcount, 2).Value
    Count = 0                     'reset the counter 
    Cells(rcount, 2).Select
      For ccount = 1 To 11
         Deletedname = ActiveCell.Offset(0, ccount).Value
         If Len(Trim$(Deletedname)) > 0 Then
             ccount = 11
         Else
             Count = Count + 1
             If Count = 11 Then
                Rows(rcount).EntireRow.Delete
             End If
         End If
      Next ccount
  Next