VBA code to clean simple data in an Excel worksheet


 Option Explicit


Sub CleanData()

    ' Remove extra spaces, leading/trailing spaces, and non-printable characters from the selected cells

    

    Dim cell As Range

    For Each cell In Selection.Cells

        ' Remove extra spaces

        cell.Value = WorksheetFunction.Trim(Replace(cell.Value, "  ", " "))

        

        ' Remove leading/trailing spaces

        cell.Value = Trim(cell.Value)

        

        ' Remove non-printable characters

        cell.Value = WorksheetFunction.Clean(cell.Value)

    Next cell

End Sub

This code defines a subroutine CleanData that cleans up the text in the currently selected cells. It removes extra spaces (replacing consecutive spaces with a single space), leading/trailing spaces, and non-printable characters. To use this code, simply select the cells containing the data you want to clean, and then run the CleanData macro.

Note that this code only works with text data in Excel. If you want to clean up numeric data, you may need to use different techniques depending on the specific data format and cleaning requirements.

Post a Comment

0 Comments
* Please Don't Spam Here. All the Comments are Reviewed by Admin.