• Replace characters (2000/XP)

    Author
    Topic
    #418702

    Hi,
    I want to automatically replace a “space” with a “_” when the user enters data in a cell (name field).
    If they enter John Smith, I want the entry to change to John_Smith.
    I tried using the substitute function but got a circular reference message.
    Thanks,
    Scott

    Viewing 0 reply threads
    Author
    Replies
    • #943158

      Say that you want to do this for cell A2.
      – Right-click the sheet tab.
      – Select View Code from the shortcut menu that pops up.
      – Copy the following code into the module:

      Private Sub Worksheet_Change(ByVal Target As Range)
      If Not Intersect(Target, Range(“A2”)) Is Nothing Then
      Range(“A2”) = Replace(Range(“A2″), ” “, “_”)
      End If
      End Sub

      • #943161

        Hans,
        Thanks. That worked but I should have specified that I want that to happen for any value in A4 to A100
        Can the code be modified for that range.
        Thanks

        • #943163

          Loop through the cells:

          Private Sub Worksheet_Change(ByVal Target As Range)
          Dim oCell As Range
          If Not Intersect(Target, Range(“A4:A100”)) Is Nothing Then
          For Each oCell In Intersect(Target, Range(“A4:A100″)).Cells
          oCell = Replace(oCell, ” “, “_”)
          Next oCell
          End If
          End Sub

          • #943167

            Hans,
            Thanks again. Thats just what I needed.
            Scott

          • #943185

            I would recommend disabling the events to prevent recursive calls to the procedure

            Private Sub Worksheet_Change(ByVal Target As Range)
                Dim oCell As Range
                If Not Intersect(Target, Range("A4:A100")) Is Nothing Then
                    Application.EnableEvents = False
                    For Each oCell In Intersect(Target, Range("A4:A100")).Cells
                        oCell = Replace(oCell, " ", "_")
                    Next oCell
                    Application.EnableEvents = True
                End If
            End Sub

            Steve

    Viewing 0 reply threads
    Reply To: Replace characters (2000/XP)

    You can use BBCodes to format your content.
    Your account can't use all available BBCodes, they will be stripped before saving.

    Your information: