Skip to main content
1 of 2

Just wanted to let you guys know that, after combining both M.Doerner and PeterT's answers, my code now looks as follows. It is actually bigger than before, but it surely is faster (and hopefully more organized). Thanks again for the feedback. Here is the code:

Option Explicit
Sub RemoveAllForbiddenCharacters()

    Const FIRST_ROW = 2
    Const TARGET_COLUMN = "J"
    Const REGEX_PATTERN = "[\\/:%'*?<>|"".]"
    Const REGEX_REPLACE = ""
    
    Call RemoveCharactersWithRegExp(FIRST_ROW, TARGET_COLUMN, REGEX_PATTERN, REGEX_REPLACE)

End Sub

Private Sub RemoveCharactersWithRegExp(lngFirstRow As Long, strColumn As String, strPattern As String, strReplace As String)

    Dim regEx As New RegExp
    With regEx
        .Global = True
        .MultiLine = True
        .IgnoreCase = False
        .Pattern = strPattern
    End With

    Dim ws As Worksheet
    Dim lngLastRow As Long
    Dim rngCells As Range
    Dim dataValues As Variant

    For Each ws In ThisWorkbook.Worksheets

        lngLastRow = ws.Cells(ws.Rows.Count, strColumn).End(xlUp).Row
        Set rngCells = ws.Range(strColumn & lngFirstRow).Resize(lngLastRow - lngFirstRow + 1, 1)
        dataValues = rngCells.Value2

        Dim i As Long
        For i = LBound(dataValues) To UBound(dataValues)
            dataValues(i, 1) = regEx.Replace(dataValues(i, 1), strReplace)
        Next

        rngCells.Value2 = dataValues

    Next

End Sub