vba宏显示循环到msgbox的结果

时间:2018-09-20 08:57:47

标签: excel vba excel-vba

我创建了一个循环,以条件检查字符数,但是很遗憾,它不能正常工作, 与适当的编号。的循环,但不读取下一行,我想将结果发布到MsgBox中, 但是当我在循环中使用msgbox时,我将为找到的每个结果得到一个msgbox,或者只有一个有一个结果的msgbox。

我想要在1个msgbox中显示每个结果,并在每个结果之后显示一行vbNewLine。

下面是我的代码:

    Public Sub Rs()

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

        Application.ScreenUpdating = False
        'Get Cell Value
        Text = Range("B2").Value
        'Get Char Length
        NumChar = Len(Text)
        NumRows = Range("B2", Range("B2").End(xlDown)).Rows.Count
        Range("B2").Select

        For i = 1 To NumRows
            'Character length validation
            If Len(Text) <= 15 Then
                    MsgBox Chr(149) & "     SVC_DESC " & Text & " has " & NumChar & " characters " & " and it's Valid !" & vbNewLine
                Else
                    MsgBox Chr(149) & "     SVC_DESC " & Text & " has " & NumChar & " characters " & " and Exceeded allowable number of characters!" & vbNewLine
            End If
          Next i
          Application.ScreenUpdating = True

    End Sub

2 个答案:

答案 0 :(得分:2)

将新文本分配给一个字符串变量,并在循环外显示该字符串变量:

Option Explicit

Sub TestMe()

    Dim i As Long
    Dim displayText As String

    For i = 1 To 3
        displayText = displayText & vbCrLf & i
    Next i

    MsgBox displayText

End Sub

enter image description here

答案 1 :(得分:1)

通过串联构建字符串,并在退出循环后显示字符串。

Public Sub Rs()

    Dim Text As String
    Dim NumChar As String
    Dim i As Integer
    Dim NumRows As Long
    dim msg1 as string, msg2 as string

    Application.ScreenUpdating = False
    'Get Cell Value
    Text = Range("B2").Value
    'Get Char Length
    NumChar = Len(Text)
    NumRows = Range("B2", Range("B2").End(xlDown)).Rows.Count
    Range("B2").Select

    For i = 1 To NumRows
        'Character length validation
        If Len(Text) <= 15 Then
                msg1 = msg1 & Chr(149) & "     SVC_DESC " & Text & " has " & NumChar & " characters " & " and it's Valid !" & vbLF
            Else
                msg2 = msg2 & Chr(149) & "     SVC_DESC " & Text & " has " & NumChar & " characters " & " and Exceeded allowable number of characters!" & vbLF
        End If
      Next i
      Application.ScreenUpdating = True

      if cbool(len(msg1)) then
          msg1 = left(msg1, len(msg1)-1)
          MsgBox msg1
      end if
      if cbool(len(msg2)) then
          msg2 = left(msg2, len(msg2)-1)
          MsgBox msg2
      end if

End Sub

MsgBox使用Chr(10)或vbLF作为新行; vbNewLine过于矫kill过正。

相关问题