简体   繁体   中英

Reading the next line when executing the loop

I created VBA code to count the value of the characters inside the cell and then display it on a Msgbox.

To make it dynamic I inserted a loop to read entire rows until the cell is empty. The loop runs the exact number of times however it's not reading the next line.

Public Sub Rs()

    Dim Text As String
    Dim NumChar As String
    Dim i As Integer
    Dim NumRows As Long
    Dim msg1 As String

    Application.ScreenUpdating = False
    'Get Cell Value
    'Get Char Length

    Text = Range("B2" & i).Value
    NumRows = Range("B2", Range("B2").End(xlDown)).Rows.Count
    Range("B2").Select

    For i = 1 To NumRows
        Text = Range("B" & i).Value
        NumChar = Len(Text)
        'Character length validation
        If Len(Text) >= 15 Then
            msg1 = msg1 & Chr(149) & "     SVC_DESC " & Text & " has " & NumChar & " characters " & " and Exceeded allowable number of characters!" & vbLf

        Else
            msg1 = msg1 & Chr(149) & "     SVC_DESC " & Text & " has " & NumChar & " characters " & " and it's Valid !" & vbLf

        End If
    Next i
    Application.ScreenUpdating = True

    MsgBox msg1

End Sub

Move Text = Range("B2").Value inside the loop and iterate the cell it gets its value from if you expect to use it in the message.

Option Explicit

Public Sub Rs()

    Dim txt As String, msg1 As String
    Dim numRows As Long, numChar As Long, i As Long

    Application.ScreenUpdating = False

    numRows = Cells(Rows.Count, "B").End(xlUp).Row

    For i = 2 To numRows
        txt = Cells(i, "B").Value2
        numChar = Len(txt)
        'Character length validation
        If numChar >= 15 Then
                msg1 = msg1 & Chr(149) & "     SVC_DESC " & txt & " has " & numChar & " characters " & " and it's Valid !" & vbLf
            Else
                msg1 = msg1 & Chr(149) & "     SVC_DESC " & txt & " has " & numChar & " characters " & " and Exceeded allowable number of characters!" & vbLf
        End If
      Next i
      Application.ScreenUpdating = True


      MsgBox msg1
End Sub

As mentioned in my comment below, msg is 'Exceeded allowable number of characters' if the numchars is less than 15? That seems counterintuitive. You could change the criteria to If numChar < 15 Then or interchange the two messages.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM