替换根据字符串的长度给出不同的结果

时间:2017-06-08 13:56:42

标签: excel-vba vba excel

我使用以下代码将以美国格式(0.8)输入的值转换为propper格式(0,8)。

For row = 2 To rowg For col = 7 To 8 If InStr(wsg.Cells(row, col), ".") > 0 Then wsg.Cells(row, col).Value = Replace(wsg.Cells(row, col), ".", ",") End If Next col Next row

这通常很有效,除了有4个小数位的情况。在19.1991的情况下,它转换为191991,而不是19,1991。完成此操作后,单元格的格式也会自动更改为数字格式,而不是我在代码中设置的文本格式。对于具有1或2位小数的值,这不会发生。

2 个答案:

答案 0 :(得分:1)

您可以使用CDbl使用区域设置将Replace返回的字符串强制转换为Double,而不是使用VBA的美国默认值:

wsg.Cells(row, col).Value = CDbl(Replace(wsg.Cells(row, col), ".", ","))

答案 1 :(得分:0)

添加单引号'

For Row = 2 To rowg
    For col = 7 To 8
        If InStr(wsg.Cells(Row, col), ".") > 0 Then
            wsg.Cells(Row, col).Value = "'" & (Replace(wsg.Cells(Row, col), ".", ","))
        End If
    Next col
Next Row

For Row = 2 To rowg
    For col = 7 To 8
        If InStr(wsg.Cells(Row, col), ".") > 0 Then
            wsg.Cells(Row, col).NumberFormatLocal = "@"
            wsg.Cells(Row, col).Value = (Replace(wsg.Cells(Row, col), ".", ","))
        End If
    Next col
Next Row