【问题标题】:Reading the next line when executing the loop执行循环时读取下一行
【发布时间】:2018-09-23 07:16:26
【问题描述】:

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

【问题讨论】:

    标签: excel vba


    【解决方案1】:

    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
    

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

    【讨论】:

    • @Gabriel,如果 numchars 小于 15,为什么消息是 '超过允许的字符数'?对我来说似乎倒退了。
    • 您的脚本有几个小问题。我已经重写了它并修复了所有我发现错误甚至只是“不好的做法”的东西。往上看。您可以使用我的叙述来决定如何更改生成的消息。
    • @Gabriel,提示:当您进行更改以调试或只是总体改进您的代码时,请设置里程碑,停止并删除不再具有任何意义的旧代码。在继续开发改进的同时留下大量代码位简直令人困惑。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-07-29
    • 1970-01-01
    • 1970-01-01
    • 2018-09-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多