Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replacing commas with dots in Excel script

Tags:

excel

vba

I want to replace a comma with dot and vice-versa

Public Sub VirgulaPunct()
Dim oRow As Range
Dim cell As Range
Dim i As Long, j As Long
Dim MyString As String
Dim aux As String

    Application.ScreenUpdating = False

    For i = Selection(Selection.Count).Row To Selection.Cells(1, 1).Row Step -1

        For j = Selection(Selection.Count).Column To Selection.Cells(1, 1).Column Step -1
            MyString = Cells(i, j).Value
            For Counter = 1 To Len(MyString)
                aux = Mid(MyString, Counter, 1)
                If aux = "." Then

                  MyString = Replace(MyString, ".", ",", 1)

                ElseIf aux = "," Then

                  MyString = Replace(MyString, ",", ".", 1)

                End If
            Next
            Cells(i, j).Value = MyString
        Next j
    Next i
    Application.ScreenUpdating = True
End Sub
like image 798
Peter Avatar asked Feb 03 '11 09:02

Peter


People also ask

How do you replace a comma with dots?

A window will open with two fields: “Find what” and “Replace with.” In the “Find what” field, type in a comma. In the “Replace with” field, type in a period/dot. Click Replace All. Clicking this option will replace every comma in the document with a period/dot.

How do you replace commas with Newline Alt enters in Excel?

Select the cells containing the commas you need to replace with newlines, then press the Alt + F11 keys simultaneously to open the Microsoft Visual Basic for Applications window. 3. Press the F5 key or click the Run button to run the code. Then all commas in selected cells are replaced with newlines immediately.

What does VBA stand for?

VBA stands for Visual Basic Analysis. Excel VBA is Microsoft's programming language for Office applications such as MS-Excel, MS-Word, and MS-Access.


1 Answers

The basic problem is that if the columns is set as general instead of text, even if we changed the "," for "." Excell automatically it will change it again for a ",".

To avoid that it is necessary to set first the column as a Text format, and then we can perform replace function:

This it works for me:

Worksheets("Name").Activate
Worksheets("Name").Columns(1).Select 'or Worksheets("SheetName").Range("A:A").Select
Selection.NumberFormat = "@"

Dim OriginalText As String
Dim CorrectedText As String

LastRow = ActiveSheet.UsedRange.SpecialCells(xlCellTypeLastCell).Row

    For i = 1 To LastRow

    OriginalText = Worksheets("Name").Cells(i, 1).Value

    CorrectedText = Replace(OriginalText, ",", ".")

    Worksheets("Name").Cells(i, 1).Value = CorrectedText

    Next i
like image 86
zosoca Avatar answered Oct 25 '22 13:10

zosoca