问题
I want to show MsgBox of fails with correspondent samples. If non show another MsgBox with no fail.
I feel I am almost there but have something messing.
If I put the MsgBox within the loop the MsgBox appears more than once, if I put it out it shows both MsgBox of "fails" if any and "There are no Fails"
How can I show only one of them with the (If-statement), and of course show once. Either box showing all fails or box showing there are none.
The code I ran:
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
回答1:
You need to feed the failsvariable with the ranges you want to show and then check if your variable is empty or not. Also, there is no need to feed a passesvariable because it will always be the same:
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
Finally, indenting correctly your code makes it more easy to read.
来源:https://stackoverflow.com/questions/56529025/how-to-show-all-fails-if-there-is-any-if-not-then-show-no-fail-box