2016-04-07 46 views
0

所以我仍然是VBA的新手,我在理解它的所有語法方面遇到了一些麻煩。我試圖循環訪問一列,看看它是否包含部分字符串。如果沒有,我需要將該行刪除。到目前爲止,我有這個:在循環中包含一個字符串的VBA單元

Private Sub CommandButton1_Click() 

Dim count As Integer 

Do While Range("H" & count).Value > 0 
    Dim exists As Integer 
    exists = InStr(1, Range("H" & count).Value, ".AB", vbTextCompare) 

    If exists > 0 Then 
     Rows(count).Delete 
    Else 
     count = count + 1 
    End If 
Loop 

End Sub 

但使用此代碼,我得到各種錯誤。首先是對象'_worksheet'的'方法範圍'失敗。有關於此的任何知識?

+2

你沒有在一開始初始化'與任何count'所以它等於0'H0'是不是一個有效的單元格。 – findwindow

+2

'count'爲0,沒有第0行。 –

+0

好的,所以我加了count = 2。但現在當我點擊按鈕時,絕對沒有任何反應。 –

回答

0

請嘗試下面的代碼

Private Sub CommandButton1_Click() 
    Dim exists As Integer 
    Dim count As Integer 
    lastrow = Range("H" & Rows.count).End(xlUp).Row 
    For i = 2 To lastrow 
     If InStr(UCase(Range("H" & i).Value), ".AB") > 0 Then 
      Rows(i).Delete 
      lastrow = lastrow - 1 
     End If 
    Next i 
End Sub 
相關問題