[英]VBA Loop Through Cells
I just started coding in VBA and I am trying to write code that goes through my sheet in Excel and, for each cell that has a value "-P", it deletes it.我刚开始在 VBA 中编码,我正在尝试编写通过我在 Excel 中的工作表的代码,并且对于每个具有值“-P”的单元格,它删除它。 Once it is done, it generates a box message that all the "-P were deleted" and that there were not any p's.完成后,它会生成一条框消息,指出所有“-P 已删除”并且没有任何 p。 It generates a message, "-P was not Found".它生成一条消息,“-P 未找到”。
The program only runs until it finds one cell and goes through the if
statement and then it is done.该程序只运行到它找到一个单元格并通过if
语句然后完成。 I would have to run it multiple times in order to delete all the p's in my document.我必须多次运行它才能删除文档中的所有 p。 I have tried for
loops and do until
loops … but I am getting more confused.我试过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
I would appreciate some help.我会很感激一些帮助。
You don't need to do this in a loop:您不需要循环执行此操作:
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.