Find all and delete in VBA

你。 提交于 2019-12-02 18:04:59

问题


I am looking for a way to find all - in a column in VBA, store them or and delete the rows?

Here is what I can use to find and delete a single row. But I need to find all of the dashes.

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

I thought about a loop but I don't know how many times to run the iteration as the number of dashes will vary.

Any suggestions would be appreciated.

Thanks,

Update- I'm not sure how to do mini markdown and make it readable so here is the updated code.

I keep getting the following error: 'ObjectVariable or 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:


As follows up from chat, this code is working:

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


来源:https://stackoverflow.com/questions/21710477/find-all-and-delete-in-vba

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!