Search code examples
excelvba

Increment number in an alphanumeric string


This working VBA code adds numbers on level columns.

For example in Sheet1, I have this table:

Name Level
Ariana Level 1
Brian Level 2

The code copies the data and changes the level to Level () + 1.

Function GetTheLastRow(sheetName As String) As Long
    'Function untuk mendapatkan row terakhir dalam sheet
    Dim sheetTarget As Worksheet
    Dim lastRow As Long
    
    Dim wb As Workbook: Set wb = ThisWorkbook
    Set sheetTarget = wb.Sheets("Existing")
    lastRow = sheetTarget.Cells(sheetTarget.Rows.Count, 1).End(xlUp).Row
    GetTheLastRow = lastRow
End Function

Sub UpDateLevel()
    With Sheets("Existing").Range("A1").CurrentRegion
        With .Resize(.Rows.Count - 1).Offset(1)
            On Error Resume Next
            Dim cel As Range
            For Each cel In Intersect(.Columns(12).SpecialCells(XlCellType.xlCellTypeVisible).SpecialCells(XlCellType.xlCellTypeConstants).EntireRow, _
              .Columns(13).SpecialCells(XlCellType.xlCellTypeConstants))
                With cel.Offset(, 2)
                    .Value = Split(.Value, " ")(0) & " " & Split(.Value, " ")(1) & " " & Split(.Value, " ")(2) & " " & Split(.Value, " ")(3) + 1
                End With
            Next
        End With
    End With

I need to add criteria:

  • Only add the number for level 1 until 3

  • Don't do any changes to level 4

Note: level would only be level 1 - 4


Solution

  • just add a check on the last value

                        With cel.Offset(, 2)
                            If Split(.Value, " ")(3) < 4 Then
                                .Value = Split(.Value, " ")(0) & " " & Split(.Value, " ")(1) & " " & Split(.Value, " ")(2) & " " & Split(.Value, " ")(3) + 1
                            End If
                        End With
    

    which you can also simplify as follows

                        With cel.Offset(, 2)
                            Dim vals As Variant
                                vals = Split(.Value, " ")
                                If vals(3) < 4 Then
                                    .Value = vals(0) & " " & vals(1) & " " & vals(2) & " " & vals(3) + 1
                                End If
                        End With