VBA 不断将句点更改为逗号

VBA keeps changing periods to commas

我制作了一个 vba 脚本,可以将特定区域的值从逗号分隔更改为点分隔。

代码如下:

Sub commas_to_periods()
'
' commas_to_periods Macro
' Convert all commas to Periods in a specified area that contains values before converting the file to csv
'

'
    Range("U3:AJ139").Select
    ' Selection.Replace What:=",", Replacement:=".", SearchOrder:=xlByColumns, MatchCase:=True
    ' Selection.Replace What:=",", Replacement:=".", LookAt:=xlPart, _
    '    SearchOrder:=xlByColumns, MatchCase:=True, SearchFormat:=False, _
    '    ReplaceFormat:=False, FormulaVersion:=xlReplaceFormula2
    
    Dim V As Variant, i As Long, j As Long, T
    V = Range("U3:AJ139").Value
    howMany = 0
    Application.ScreenUpdating = False
    T = Timer
    For i = LBound(V, 1) To UBound(V, 1)
        For j = LBound(V, 2) To UBound(V, 2)
            If InStr(V(i, j), ",") > 0 Then
                V(i, j) = Replace(V(i, j), ",", ".")
                howMany = howMany + 1
            End If
        Next j
    Next i
    Range("U3:AJ139").Value = V
    msgForBox = "That took " & Timer - T & " Seconds and found: " & howMany & " commas"
    MsgBox (msgForBox)
    Application.ScreenUpdating = True
    
End Sub

如您所见,我尝试了几种方法,但我还使用了自定义循环来计算替换次数。我就是无法让它工作!消息框显示它找到了 100 多个逗号,但是宏完成后没有任何更改。下次我 运行 它时,我会在框中收到完全相同的消息。找到相同数量的逗号 - 没有变化!

如果我尝试替换其他任何东西,它工作得很好。更换了。当我用逗号尝试时,它顽固地不起作用。现在我想这与我的区域设置有关,但我想不出解决方法。当我进行手动搜索并替换逗号时,逗号会发生变化。我什至录制了一个我进行手动搜索和替换的宏,我得到了相同的结果。 VBA 似乎恢复了我的更改以符合我的区域设置。有办法解决这个问题吗?

请注意,如果您的区域设置设置为 , 作为小数点,这意味着任何包含 . 的数字都将被视为文本。

因此,如果您希望 Excel 不将它们转换为数字,您需要确保将单元格的数字格式设置为文本:.NumberFormat = "@",然后再写入包含 [= 的数字13=]点.

例如

Sub a()
    
    Selection.NumberFormat = "@"
    Selection = Replace(Selection, ",", ".")

End Sub

对于多个单元格,您需要循环:

Sub b()   
    Dim Rng As Range
    Set Rng = Selection
    
    Rng.NumberFormat = "@"
    
    Dim Cell As Variant
    For Each Cell In Rng.Cells
        Cell.Value2 = Replace$(Cell.Value2, ",", ".")
    Next Cell
End Sub

因为任何其他解决方案都不起作用,因为 Excel 认为它很聪明并将任何文本转换回数字。