2014-02-11 51 views
0

我正在尋找一種方法來查找所有 - 在VBA列中,存儲它們或刪除行?查找全部和刪除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或利用未設定塊變量」

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

這裏是一個很好的例子使用'Do..While'循環與'Find'方法:[link](http://msdn.microsoft.com/en-us/library/office/ff839746.aspx) –

+0

查看原始文章中的代碼更新。 @simoco我還沒有完全掌握迷你Markdown格式,但感謝您的幫助。 – SASUSMC

+0

您可以使用此代碼編輯您的問題,請)這是在評論unreadeble :),也表明在哪一行代碼plesase你得到一個錯誤 –

回答

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 
+1

感謝所有幫助@simoco,那是最後一個件到一個更大的宏。 – SASUSMC