VBA单元格在循环内包含一个字符串

时间:2016-04-07 15:14:10

标签: excel vba excel-vba basic

所以我仍然是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'失败&#34 ;.对此有何了解?

1 个答案:

答案 0 :(得分: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