Home > Mobile >  Deleting instances of chars using arrays and loops
Deleting instances of chars using arrays and loops

Time:11-21

I have a column where almost every cell is made of a combination of numbers and letters and symbols ("TS-403" or "TSM-7600"). I want every char that's not an integer to be deleted/replaced with an empty string, so that I'm left only with numbers ("403").

I've thought up of two approaches:

I think the best one is to create an array of integers with the numbers 0-9, and then iterate through the cells with a for loop where if the string in a cell contains a char that's not in the array, then that symbol (not the entire cell) should be erased.

Sub fixRequestNmrs()

Dim intArr() as Integer
ReDim intArr(1 to 10)

    For i = 0 to 9
    intArr(i) = i
    Next i


Dim bRange as Range
Set bRange = Sheets(1).Columns(2)

For Each cell in bRange.Cells
if cell.Value 
// if cell includes char that is not in the intArr, 
// then that char should be deleted/replaced.
...

End Sub()

Perhaps the second approach is easier, which would be to use the Split() function as the '-' is always followed by the numbers, and then have that first substring replaced with "". I'm very confused on how to use the Split() function in combination with a range and a replace funtion though...

For Each cell in bRange.Cells
Cells.Split(?, "-")
...

CodePudding user response:

Digits to Integer Using the Like Operator

The Function

''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
' Purpose:      Returns an integer composed from the digits of a string.
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
Function DigitsToInteger(ByVal SearchString As String) As Long

    Dim ResultString As String
    Dim Char As String
    Dim n As Long
    
    For n = 1 To Len(SearchString)
        Char = Mid(SearchString, n, 1)
        If Char Like "[0-9]" Then ResultString = ResultString & Char
    Next n
    
    If Len(ResultString) = 0 Then Exit Function

    DigitsToInteger = CLng(ResultString)

End Function

A Worksheet Example

Sub DigitsToIntegerTEST()

    Const FIRST_ROW As Long = 2

    ' Read: Reference the (single-column) range.
    
    Dim wb As Workbook: Set wb = ThisWorkbook ' workbook containing this code
    Dim ws As Worksheet: Set ws = wb.Worksheets("Sheet1")
    
    Dim LastRow As Long: LastRow = ws.Cells(ws.Rows.Count, "B").End(xlUp).Row
    If LastRow < FIRST_ROW Then Exit Sub ' no data
    
    Dim rg As Range: Set rg = ws.Range("B2", ws.Cells(LastRow, "B"))
    Dim rCount As Long: rCount = rg.Rows.Count
    
    ' Read: Return the values from the range in an array.
    
    Dim Data() As Variant
    
    If rCount = 1 Then
        ReDim Data(1 To 1, 1 To 1): Data(1, 1) = rg.Value
    Else
        Data = rg.Value
    End If
    
    ' Modify: Use the function to replace the values with integers.
    
    Dim r As Long
    
    For r = 1 To rCount
        Data(r, 1) = DigitsToInteger(CStr(Data(r, 1)))
    Next r
    
    ' Write: Return the modifed values in the range.
    
    rg.Value = Data
    ' To test the results in the column adjacent to the right, instead use:
    'rg.Offset(, 1).Value = Data

End Sub

In VBA (Simple)

Sub DigitsToIntegerSimpleTest()
    Const S As String = "TSM-7600sdf"
    Debug.Print DigitsToInteger(S) ' Result 7600
End Sub

In Excel

=DigitsToInteger(A1)

CodePudding user response:

If you have the CONCAT function, you can do this with a relatively simple formula -- no VBA needed:

=CONCAT(IFERROR(--MID(A1,SEQUENCE(LEN(A1)),1),""))

If you prefer a non-VBA solution in an earlier version of Excel, there is a more complex formula available, but I'd have to go back through my files to locate it.

CodePudding user response:

A tricky function GetVal()

The following function

  • translates a string into a single characters array arr via help function String2Arr()
  • isolates them into numeric (category code 6) or non-numeric categories (other) via a tricky execution of Application.Match (here without its 3rd argument which is mostly used for precise search, and by comparing two arrays)
  • finds the starting position in the original string via Instr()
  • returns the value of the right substring via Val() (~> see note).
Function GetVal(ByVal s As String) As Double
    Dim arr:      arr = String2Arr(s):      Debug.Print Join(arr, "|")
    Dim chars:    chars = Split(" ,', ,-,.,0,A", ",")
    Dim catCodes: catCodes = Application.Match(arr, chars)  'No 3rd zero-argument!!
    Dim tmp$:     tmp = Join(catCodes, ""): Debug.Print Join(catCodes, "|")
    Dim pos&:     pos = InStr(tmp, 6)   ' Pos 6: Digits; pos 1-5,7: other symbols/chars
    GetVal = Val(Mid(s, pos))           ' calculate value of right substring
End Function

Notes

The Val function can translate a (sub)string with starting digits to a number, even if there are following non-numeric characters.

Help function String2Arr()

Atomizes a string into a single characters array:

Function String2Arr(ByVal s As String)
    s = StrConv(s, vbUnicode)
    String2Arr = Split(s, vbNullChar, Len(s) \ 2)
End Function

Example call

    Dim s As String
    s = "aA *&$%(y#,'/\)!-12034.56blabla"
    Debug.Print GetVal(s)          ' ~~> 12034.56
  • Related