2

Basically what I am trying to do is to imitate the replace button with VBA code. I use the following code:

Private Sub CommandButton1_Click()
    Blad1.Activate
    Blad1.Cells.Select
    Selection.Replace What:=".", Replacement:=",", LookAt:=xlPart, _
        SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
        ReplaceFormat:=False
End Sub

This replaces all of the dots, but in some cases it replaces the dots with whitespaces instead of commas. Why is this?

14
  • 1
    It works just fine for me. Can you give an example where it is not working? Commented Jun 13, 2012 at 7:48
  • Well, I have a lot of data, and it works fine in the first columns but when I come to column V and W it skips a lot of the cells. Commented Jun 13, 2012 at 8:02
  • would it be possible for me to see Col V/W data in a sample file? Commented Jun 13, 2012 at 8:02
  • Sure. Is it possible for me to send it too you through stackoverflow in anyway or do I need your email? Commented Jun 13, 2012 at 8:07
  • upload the file in www.wikisend.com and share the link here. Commented Jun 13, 2012 at 8:07

1 Answer 1

2

Try this

Sub Sample()
    Dim oRange As Range, aCell As Range, bCell As Range
    Dim ws As Worksheet
    Dim ExitLoop As Boolean
    Dim SearchString As String, FoundAt As String
    On Error GoTo Err
    Set ws = Blad1
    Set oRange = ws.Cells

    oRange.NumberFormat = "@"

    SearchString = "."
    Set aCell = oRange.Find(What:=SearchString, LookIn:=xlValues, _
                LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
                MatchCase:=False, SearchFormat:=False)
    If Not aCell Is Nothing Then
        Set bCell = aCell
        Do While InStr(1, aCell.Formula, ".") > 0
            aCell.Formula = Replace(aCell.Formula, ".", ",")
        Loop
        Do While ExitLoop = False
            Set aCell = oRange.FindNext(After:=aCell)

            If Not aCell Is Nothing Then
                If aCell.Address = bCell.Address Then Exit Do
                Do While InStr(1, aCell.Formula, ".") > 0
                    aCell.Formula = Replace(aCell.Formula, ".", ",")
                Loop
            Else
                ExitLoop = True
            End If
        Loop
    End If
    Exit Sub
Err:
    MsgBox Err.Description
End Sub
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you, that did work. I am guessing the thousands separator was responsible somehow, after really looking through the result I saw that only the cells with more than 4 numbers were troublesome.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.