簡體   English   中英

VBA 循環單元格

[英]VBA Loop Through Cells

我剛開始在 VBA 中編碼,我正在嘗試編寫通過我在 Excel 中的工作表的代碼,並且對於每個具有值“-P”的單元格,它刪除它。 完成后,它會生成一條框消息,指出所有“-P 已刪除”並且沒有任何 p。 它生成一條消息,“-P 未找到”。

該程序只運行到它找到一個單元格並通過if語句然后完成。 我必須多次運行它才能刪除文檔中的所有 p。 我試過for循環和do until循環……但我越來越困惑了。

Sub RemoveP()

    Dim ws As Worksheet
    Dim xcell As Object
    Dim rng As Range

    Set ws = Worksheets(1)
    Set rng = ws.Range("B:B")
    
    For Each xcell In rng
        If xcell Is Nothing Then
            MsgBox "-P was not Found"
        Else
            xcell.Replace What:="-P", Replacement:="", lookAt:=xlPart, SearchOrder:=xlByColumns, _
            MatchCase:=False, SearchFormat:=False, ReplaceFormat:=False
                  
                MsgBox "-P was Deleted"
        End If
            
    Next xcell
      
End Sub

我會很感激一些幫助。

您不需要循環執行此操作:

Sub RemoveP()

    Dim ws As Worksheet
    Dim rng As Range

    Set ws = Worksheets(1)
    'only work on the occupied part of the column
    Set rng = ws.Range("B1:B" & ws.Cells(Rows.Count, "B").End(xlUp).Row)
    
    If Not IsError(Application.Match("*-p*", rng, 0)) Then 'any -P in rng?
        rng.Replace What:="-P", Replacement:="", lookAt:=xlPart, _
                   SearchOrder:=xlByColumns, MatchCase:=False, _
                   SearchFormat:=False, ReplaceFormat:=False
        MsgBox "-P was Deleted"
    Else
        MsgBox "-P was not Found"
    End If
    
End Sub

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM