Arup Rakshit
Arup Rakshit

Reputation: 118271

Sparse matrix creation using vbscript

Suppose I have an Array={A,B,Y,X}. Now I do have an Excel sheet which can have dynamic number of columns and Rows.Say as an example below :

Input:

ColA   ColB   ColC  ....

 T      P      Y    ....
 C      Y      D    ....
 B      A      M    ....
 Z      R      X    ....

OutPut:

ColA   ColB   ColC  ....

 -      -      Y    ....
 -      Y      -    ....
 B      A      -    ....
 -      -      X    ....

Where all the columns will have only the Array values,if any other values are found they are required to be replaced by "-"

Is there any faster process to do these using VBscript except comparatively slow looping technique?

Thanks,

Upvotes: 0

Views: 1197

Answers (1)

Tim Williams
Tim Williams

Reputation: 166341

Sub Macro1()

    Dim arr, i, rng As Range

    arr = Array("X", "Y", "Z")
    Set rng = ActiveSheet.Range("A1").CurrentRegion

    With Application
        .ScreenUpdating = False
        .Calculation = xlCalculationManual
    End With

    For i = LBound(arr) To UBound(arr)
        rng.Replace What:=arr(i), Replacement:="-", LookAt:=xlWhole, _
            SearchOrder:=xlByRows, MatchCase:=True, SearchFormat:=False, _
            ReplaceFormat:=False
    Next i

    With Application
        .ScreenUpdating = True
        .Calculation = xlCalculationAutomatic
    End With

End Sub

EDIT:

Sub KeepValues()

    Dim arr, arrVals, i, rng As Range, r, c
    Dim keepval As Boolean

    arr = Array("X", "Y", "Z")

    Set rng = ActiveSheet.Range("A1").CurrentRegion
    arrVals = rng.Value

    For r = 1 To UBound(arrVals, 1)
        For c = 1 To UBound(arrVals, 2)
            keepval = False
            For i = LBound(arr) To UBound(arr)
                If arr(i) = arrVals(r, c) Then
                    keepval = True
                    Exit For
                End If
            Next i
            If Not keepval Then arrVals(r, c) = ""
        Next c
    Next r

    rng.Value = arrVals

End Sub

Upvotes: 1

Related Questions