执行循环时读取下一行

时间:2018-09-23 07:16:27

标签: excel vba

我创建了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

1 个答案:

答案 0 :(得分:0)

如果要在消息中使用它,请在循环内移动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,则味精为“超出允许的字符数”?这似乎违反直觉。您可以将条件更改为If numChar < 15 Then 交换两条消息。