简体   繁体   English

执行循环时读取下一行

[英]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. 我创建了VBA代码以计算单元格内字符的值,然后将其显示在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. 如果希望在消息中使用它,则在循环内移动Text = Range("B2").Value并迭代从中获取其值的单元格。

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? 正如我在下面的评论中所提到的,如果numchar小于15,则msg为“超出了允许的字符数”? That seems counterintuitive. 这似乎违反直觉。 You could change the criteria to If numChar < 15 Then or interchange the two messages. 您可以将条件更改为If numChar < 15 Then 交换两个消息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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