Excel批量删除单元格指定文本问题及VBA代码排查求助
Let's walk through the issues in your code and get it working properly:
1. Using cell.Text instead of cell.Value
The biggest problem here is relying on cell.Text for the replacement. cell.Text returns what's displayed in the cell (which can be affected by formatting like column width truncation), while cell.Value accesses the actual stored value in the cell. Since you need to modify the underlying data, you should always use cell.Value for this kind of operation.
2. Unnecessary Count:=2 parameter
Your target string "123 456" only appears once in each cell ("123 456 7"). Setting Count:=2 tells VBA to replace the string twice, which doesn't make sense here—there's only one occurrence to remove. You can either set Count:=1 (explicitly replace once) or omit the parameter entirely (since the default is to replace all occurrences, which works just as well here).
Corrected Code
Here's the fixed version that will reliably remove "123 456" from each cell in A1:A3:
Sub RemoveText() Dim cell As Range For Each cell In Range("A1:A3") ' Use cell.Value instead of cell.Text, and remove the unnecessary Count parameter cell.Value = Replace(cell.Value, "123 456", "") ' Optional: Trim leading/trailing spaces if you want "7" instead of " 7" cell.Value = Trim(cell.Value) Next End Sub
If you want to avoid the leading space entirely (since replacing "123 456" leaves a space before the "7"), you can adjust the search string to include the trailing space:
cell.Value = Replace(cell.Value, "123 456 ", "")
This will directly turn "123 456 7" into "7" without needing the Trim step.
内容的提问来源于stack exchange,提问作者trill

