我有一个列,其中包含从 CSV 文件中获取的数据,该数据包含我需要删除的点。当我想用 VBA 将“.”(点)替换为“”(无)时,我得到了错误的结果。所有小于 1000 的数字都会替换逗号,例如我有 122,49,结果是 12249,这是错误的。 我尝试了几个 VBA 代码,但没有一个有效。 如果你能帮助我那就太好了。我尝试了所有格式选项..
谢谢。
- 2.078,00 -> 2078,00 好的
- 122,49 -> 12249 科
- 328,28 -> 32828 科
- 11.192,34 -> 11192,34 好的
Sub TEST() Dim i As String Dim k As String i = "." k = "" Columns("P:P").Replace what:=i, replacement:=k, lookat:=xlPart, MatchCase:=False End Sub
最佳答案
实际上这是Excel中的一个错误!它只发生在 VBA 中。如果您从用户界面执行相同的替换,它就会起作用。录制的宏中的相同操作失败。很明显是一个错误。
我建议将所有值读入一个数组,然后替换,然后写回。这样就不会发生错误,并且使用数组甚至比使用范围更快。
Option Explicit
Sub TEST()
Dim i As String
Dim k As String
i = "."
k = ""
Dim LastRow As Long 'find last used row (to reduce processed cells)
LastRow = Cells(Rows.Count, "P").End(xlUp).Row
Dim ReplaceValues() As Variant 'read all values into array
ReplaceValues = Range("P1:P" & LastRow).Value
Dim iRow As Long 'replace
For iRow = LBound(ReplaceValues) To UBound(ReplaceValues)
ReplaceValues(iRow, 1) = Replace(ReplaceValues(iRow, 1), i, k)
Next iRow
'write all values from array back into cells
Range("P1:P" & LastRow).Value = ReplaceValues
End Sub
或者,使用Application.Substitute
:
Sub Test()
Dim lr As Long
Dim arr As Variant
lr = Cells(Rows.Count, "P").End(xlUp).Row
arr = Range("P1:P" & lr).Value
Range("P1:P" & lr).Value = Application.Substitute(arr, ".", "")
End Sub
关于excel - 删除字符串中的点,数字 < 1000 时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61231000/