2017-09-11 82 views
3

我有一個包含某些組件規範的2列。 基本上,我想刪除整個行如果兩個指定的列的首字母是S.不同如果行的一個單元格以某個字符串開頭,則VBA Excel將刪除行

我的表看起來像這樣

enter image description here

我想刪除的每一行,如果列「from device」AND「to device」以G或C開頭(或者更具體地說,如果「from」和「to」中的任一列以S開始,保留整行),我的代碼如下:

Sub FilterData2() 

Dim rcount As Long 

With Sheet3 
    rcount = Range("B" & Rows.Count).End(xlUp).Row 
    With Range("E1:E" & rcount) 
     If Application.WorksheetFunction.CountIf(Columns(5), "C*") > 0 Then 
      .AutoFilter field:=1, Criteria1:="C*" 
      .Offset(1).Resize(.Rows.Count - 1, 1).EntireRow.Delete 
      .AutoFilter 
     End If 
     If Application.WorksheetFunction.CountIf(Columns(5), "G*") > 0 Then 
      .AutoFilter field:=1, Criteria1:="G*" 
      .Offset(1).Resize(.Rows.Count - 1, 1).EntireRow.Delete 
      .AutoFilter 
     End If 
     End With 
    End With 

End Sub 

如何這隻適用於列E,這意味着如果列G包含一個以S開始並且E列沒有的單元格,該行仍然會被刪除,並且我想保留該行。

有什麼建議嗎?謝謝!

+0

你正在使用你的If語句就在列E'帶範圍(「E1:E」&rcount)' – danieltakeshi

+0

我試過使用instr,但它幾乎刪除了所有內容,因爲幾乎每個單元格都包含「C」或「G」並且我不知道如何指定我希望它只是第一個字符 – Monojoll

回答

3

你可以在VBA中結合你的if語句。

使用和修改:

If Application.WorksheetFunction.CountIf(Columns(5), "C*") > 0 AND Application.WorksheetFunction.CountIf(Columns(5), "G*") > 0 Then 

同樣,你可以使用一個或modifier:

If Application.WorksheetFunction.CountIf(Columns(5), "C*") > 0 OR Application.WorksheetFunction.CountIf(Columns(5), "G*") > 0 Then 

若要將此到您的代碼,在那裏你只是想看看,如果單元格的內容開始其中S在或者從或到:

Dim rcount As Long 
Dim i As Integer 
Dim strE, strG As String 

With Sheets("Sheet3") 
    rcount = .Range("B" & Rows.Count).End(xlUp).Row 

    For i = rcount to 2 Step -1 
     strE = Left(.Cells(i, "E").Value, 1) 
     strG = Left(.Cells(i, "G").Value, 1) 
     If strE = "S" Or strG = "S" Then 
     Else 
      .Rows(i).EntireRow.Delete 
     End If 
    Next i 
End With 

這應該顯着簡化過程。

+0

這工作正常!我試圖使用左爲朋友推薦它,但我仍然在搞清楚語法。謝謝! – Monojoll

+0

@JeanCarlo無後顧之憂。我可能會推薦一個更改,因爲即使我在通過代碼工作時錯過了這一點:* rcount = .cells(.rows.count,「B」)。End(xlUp).Row *我錯過了.Rows.Count沒有找到' t也指定表格(「Sheet3」)。 – Cyril

相關問題