excel - 删除字符串中的点,数字 < 1000 时出现问题

标签 excel vba numbers

我有一个列,其中包含从 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

wrong result

最佳答案

实际上这是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/

相关文章:

excel - 为什么我的选项按钮没有切换组合框文本?

来自另一张纸的 VBA 循环

Excel:使用其他工作表中的某些单元格创建摘要工作表

excel - 将单元格从一般格式设置为文本

localization - 除了英语之外,还有其他语言为阿拉伯数字附加后缀吗?

python - 读取非常大的一行文本文件

VBA:获取运行时 1004:使用单元格时对象 'Range' 的方法 '_Worksheet' 失败

VBA EXCEL 提示用户响应选择文件夹并将路径作为字符串变量返回

c# - 从Excel读取时如何计算空行

java - java中如何生成随机数