仅在字符串中的特定位置用逗号(,)替换逗号(,)

时间:2017-10-25 08:41:04

标签: excel excel-vba vba

我在多行上都有字符串,看起来像这样

S087A1097,99,86,0,14,0,good
S087A1097,100,0,10,14,0,good
S087A1097,0,0,100,0,0,good

我需要分别改变它。

S087A1097,99.86,0.14,0,good
S087A1097,100.0,10.14,0,good
S087A1097,0.0,100.0,0,good

如何在Excel中实现此目的

2 个答案:

答案 0 :(得分:2)

如果您的文字在单元​​格A1中:

=SUBSTITUTE(SUBSTITUTE(A1,",",".",2),",",".",3)

答案 1 :(得分:0)

如果您想使用VBA解决方案,可以尝试以下代码。

它可能看起来有点长,但执行速度非常快,因为工作表几乎没有“搞乱”,而且大部分逻辑都是在数组上完成的。

<强>代码

Option Explicit

Sub ImportCsvContents()

Dim csvLines As Variant, CurrentRow As Variant
Dim LastRow As Long, i As Long

ReDim csvLines(0)

With Worksheets(1)
    LastRow = .Cells(.Rows.Count, "A").End(xlUp).Row

    ' === logic, each order ends with data data in column "B" ===
    For i = 1 To LastRow
        csvLines(UBound(csvLines)) = .Range("A" & i).Value
        ReDim Preserve csvLines(UBound(csvLines) + 1) ' keep record and raise array index by 1
    Next i
End With

' resize array to actual populated size
If csvLines(UBound(csvLines)) = "" Then
    ReDim Preserve csvLines((UBound(csvLines) - 1))
End If


' loop through all lines in .csv file
For i = 0 To UBound(csvLines)
    CurrentRow = Split(csvLines(i), ",")

    CurrentRow(1) = CurrentRow(1) & "." & CurrentRow(2)
    CurrentRow(2) = CurrentRow(3) & "." & CurrentRow(4)
    CurrentRow(3) = CurrentRow(5)
    CurrentRow(4) = CurrentRow(6)

    ' re-format the current line
    csvLines(i) = CurrentRow(0) & "," & CurrentRow(1) & "," & CurrentRow(2) & "," & CurrentRow(3) & "," & CurrentRow(4)

    Erase CurrentRow ' clear array
Next i

' now just dump the entre array to the worksheet
Worksheets(1).Range("A1").Resize(UBound(csvLines) + 1).Value = Application.Transpose(csvLines)

End Sub