Quantcast
Channel: Active questions tagged excel - Stack Overflow
Viewing all articles
Browse latest Browse all 88030

Clean,Trim-VBA errors (removed filtered data, leaves #NA, does not work on big data)

$
0
0

I have used this VBA below with success to clean and trim exported data.

I have started to see 3 problems.

  1. I have started to use it on data formatted as tables and when the table is filtered the script removes rows. Should I add a portion to the Script that removes any filter in the list first or is it another way?
  2. Another issue is that it ends if the data amount is huge. Do you see any errors that I have missed in the Script?
  3. The third issue I have notices is that many #Value or #NA pops up in the data. Can this be avoided?
Sub CallCleanTrimExcel()
    Dim MasterFile As Workbook

    Dim SurveyRptName As String
    Dim SurveyReport As Workbook

    Set MasterFile = ThisWorkbook '

    SurveyRptName = Application.GetOpenFilename("Excel files (*.xlsx), *xlsx", 1, _
        "Please select the data you want to cleanse.", , False)
    If SurveyRptName <> "False" Then
        Set SurveyReport = Workbooks.Open(SurveyRptName)
    End If

    SurveyReport.Activate

Dim rng As Range
Dim Area As Range
Dim rngTemp As Range

Set rngTemp = Cells.Find("*", SearchOrder:=xlByRows, SearchDirection:=xlPrevious)
If Not rngTemp Is Nothing Then
    Range(Cells(1, 1), rngTemp).Select
End If

    Dim arr() As Variant
    Dim m As Double
    Dim n As Double

    arr = Selection.Value

    For m = LBound(arr, 1) To UBound(arr, 1)
        For n = LBound(arr, 2) To UBound(arr, 2)
            arr(m, n) = CleanTrimExcel(arr(m, n))
        Next n
    Next m

    Selection = arr()

ActiveSheet.Cells.NumberFormat = "General"

MsgBox "Cleaning done!"

End Sub
Function CleanTrimExcel(ByVal S As String, Optional ConvertNonBreakingSpace As Boolean = True) As String

    Dim X As Long
    Dim CodesToReplace() As Variant

    If ConvertNonBreakingSpace Then
        ReDim CodesToReplace(1 To 7)
        CodesToReplace = Array(127, 129, 141, 143, 144, 157, 160)
    Else
        ReDim CodesToReplace(1 To 6)
        CodesToReplace = Array(127, 129, 141, 143, 144, 157)
    End If

    For X = LBound(CodesToReplace) To UBound(CodesToReplace)
        If InStr(S, Chr(CodesToReplace(X))) Then S = Replace(S, Chr(CodesToReplace(X)), Chr(0))
    Next

    CleanTrimExcel = WorksheetFunction.Trim(WorksheetFunction.Clean(S))

End Function

Viewing all articles
Browse latest Browse all 88030

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>