在VBA中查找全部并删除

时间:2014-02-11 18:47:28

标签: vba for-loop excel-2010

我正在寻找一种方法来查找所有 - 在VBA的列中,存储它们或删除行?

以下是我可以用来查找和删除单行的内容。但我需要找到所有破折号。

Dim A as Long

    Columns("C:C").Select
    Selection.Find(What:="-", After:=ActiveCell, LookIn:=xlValues, LookAt:= _
        xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:=False _
        , SearchFormat:=False).Activate
     A = ActiveCell.Row
     Range(A).Delete

我想过一个循环,但我不知道运行迭代的次数,因为破折号的数量会有所不同。

任何建议都将不胜感激。

谢谢,

更新 - 我不确定如何进行迷你降价并使其可读,所以这里是更新的代码。

我一直收到以下错误:'ObjectVariable或With block Variable not set'

Dim LastRow As Long

'Find the last used row in a Column: column A
 With ActiveSheet
        LastRow = .Cells(.Rows.Count, "A").End(xlUp).Row
 End With

'
 With Worksheets(5).Range("c1:c1500")
    Set c = .Find("-", LookIn:=xlValues)
    If Not c Is Nothing Then
        firstAddress = c.Address
        Do
            c.Value = "John"
            Set c = .FindNext(c)
        Loop While Not c Is Nothing And c.Address <> LastRow
    End If
End With

1 个答案:

答案 0 :(得分:0)

从聊天开始,这段代码正常运行:

Sub test()
    Dim firstAddress As String
    Dim c As Range
    Dim rngToDelete As Range

    With Worksheets(5).Range("c1:c1500")
       Set c = .Find("-", LookIn:=xlValues)
       If Not c Is Nothing Then
           firstAddress = c.Address
           Do
               If rngToDelete Is Nothing Then
                  Set rngToDelete = c
               Else
                  Set rngToDelete = Union(rngToDelete, c)
               End If
               Set c = .FindNext(c)
               If c Is Nothing Then Exit Do
           Loop While c.Address <> firstAddress
       End If
    End With

    If Not rngToDelete Is Nothing Then rngToDelete.EntireRow.Delete
End Sub