Search code examples
excelmsgboxvba

Displaying MsgBox when range of cells have not a specific length


I have a program in which a label is scanned and that value goes into a cell, but for security reasons, it's necessary to check that the length of this is always the same (for example: 8, label=12345-78) the string has a "-" in it. What I want the program to do is that, when the scanned label has a number different than this one, display a messagebox that indicates that the number is invalid and then erase the cell's content. I would really appreciate some help with this.

Here's the code I have so far:

Private Sub Worksheet_Change(ByVal Target As Range)
'macro para prohibir longitud que no sea la seleccionada

Dim rango As Range


For Each Range In Worksheets("HojadeInspection").Range("I9:I20")


If rango.Len(c.Value) <> 8 Then

MsgBox "La longitud del código insertado no es la correcta", vbcrtical


End If



End Sub

Solution

  • Dim i As Integer
    
    'I is the column I used, switch it to meet your needs
    
    i = Worksheets("Sheet1").Range("I:I").Cells. _
         SpecialCells(xlCellTypeConstants).Count
    
    If Not Len(Range("I" & CStr(i))) = 8 Then
    
    MsgBox "Your Message Here", vbCritical
    End If
    
    End Sub
    

    (Code edited from original response)