【问题标题】:How to show all fails if there is any, if not then show no fail box如果有任何失败,如何显示所有失败,如果没有,则显示没有失败框
【发布时间】:2019-06-10 15:12:12
【问题描述】:

我想用对应的样本显示失败的 MsgBox。如果不显示另一个没有失败的 MsgBox。

我觉得我快到了,但有些事情搞砸了。

如果我将 MsgBox 放入循环中,则 MsgBox 会出现不止一次,如果我把它放出来,它会同时显示 MsgBox 的“失败”(如果有)和“没有失败”

我怎样才能用(If 语句)只显示其中一个,当然也显示一次。显示全部失败的框或显示没有的框。

我运行的代码:

Sub Box()
Dim x As Long
Dim fails As String
'Dim passes As String

With Sheet2
    For x = 2 To 8
        If .Range("E" & x).Value > 0.24 Then
        fails = fails & ", " & .Range("A" & x)
        MsgBox "Failed Strut: " & fails
        ElseIf .Range("E" & x).Value < 0.24 Then
        passes = "There are no fails"
        MsgBox passes
        End If
    Next x
End With

'Other attempts
'MsgBox passes
'fails = Right(fails, Len(fails) - 2)
'MsgBox "Failed Strut: " & fails

End Sub

【问题讨论】:

标签: excel vba msgbox


【解决方案1】:

您需要向failsvariable 提供要显示的范围,然后检查您的变量是否为空。此外,无需提供 passesvariable,因为它始终是相同的:

Option Explicit
Sub Box()
    Dim x As Long
    Dim fails As String
    'Dim passes As String

    With Sheet2
        For x = 2 To 8
            If .Range("E" & x).Value > 0.24 Then
                If fails = vbNullString Then
                    fails = .Range("A" & x)
                Else
                    fails = fails & ", " & .Range("A" & x)
                End If
            End If
        Next x
    End With

    'Here you check wether you send one message or the other
    If Not fails = vbNullString Then
        MsgBox "Failed Strut: " & fails
    Else
        MsgBox "There are no fails"
    End If

    'Other attempts
    'MsgBox passes
    'fails = Right(fails, Len(fails) - 2)
    'MsgBox "Failed Strut: " & fails

End Sub

最后,正确缩进代码会让代码更易于阅读。

【讨论】:

  • 非常感谢!完美运行。如果没有失败,我将如何删除标题“,”而不会出错。我使用 (fails = Right(fails, Len(fails) - 2)) 但如果没有任何失败可能会显示错误
  • @Moe 如果我理解正确,我的编辑应该会有所帮助。
猜你喜欢
  • 2017-04-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-10-08
  • 2022-07-21
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多