繁体   English   中英

执行循环时读取下一行

[英]Reading the next line when executing the loop

我创建了VBA代码以计算单元格内字符的值,然后将其显示在Msgbox上。

为了使其动态,我插入了一个循环以读取整行,直到单元格为空。 循环将运行确切的次数,但是不会读取下一行。

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

如果希望在消息中使用它,则在循环内移动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

正如我在下面的评论中所提到的,如果numchar小于15,则msg为“超出了允许的字符数”? 这似乎违反直觉。 您可以将条件更改为If numChar < 15 Then 交换两个消息。

暂无
暂无

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

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