Search code examples
vbaif-statementstring-length

VBA IF cell VALUE LENGTH criteria


I have a code:

IF s LIKE "UZL.*" AND s LIKE "*.ENG" THEN

It evaluates if cell value starts with "UZL." and ends with ".ENG" but I would like to change those second criteria ".ENG" to be cell length =16 symbols. So it's like

If s Like "UZL.*" And cell value length =16 Then

Can someone please say what would be the code for that?

Full code:

Dim vDB As Variant
Dim rngDB As Range
Dim s As String, sReplace As String
Dim i As Long
Dim Ws As Worksheet

Set Ws = Sheets("BOM")

On Error Resume Next
Worksheets("BOM").ShowAllData
 
With Ws
    Set rngDB = .Range("E2", .Range("E" & Rows.Count).End(xlUp))
End With
vDB = rngDB
For i = 1 To UBound(vDB, 1)
    s = vDB(i, 1)
    If s Like "UZL.*" And s Like "*.ENG" Then
        sReplace = Me.LanguageBox.Value
        s = Replace(s, "ENG", sReplace)
        vDB(i, 1) = s
    End If
Next i
rngDB = vDB

Workbook: https://easyupload.io/37tztt


Solution

  • I'm not a super expert on this matter but I believe you can use LEN function to obtain the text length.

    I believe this should work:

    If s Like "UZL.*" And Len(s.value) = 16 Then
    

    UPDATE:

    I've made a test locally and len function should be ok if s variable is in fact a string:

    Sub Teste()
        
        s = "test"
        
        'First test
        If s Like "tes*" And Len(s) >= 4 Then
            Debug.Print "First Test: OK"
        End If
        
        'Second test
        If s Like "tes*" And Len(s) < 4 Then
            Debug.Print "Second Test: OK"
        Else
            Debug.Print "Second Test: NOK"
        End If
        
    End Sub
    

    Console Output:

    • First Test: OK
    • Second Test: NOK