【问题标题】:MsgBox Appears multiple times...reaarange macro so it is only displayed onceMsgBox 出现多次...reaarange 宏所以它只显示一次
【发布时间】:2013-09-27 11:24:20
【问题描述】:

我有一个脚本可以查看整个列并查找 1 到 9 之间的值,如果遇到一个数字,它会抛出一个消息框,如果它当前没有抛出 10 个消息框,我知道这是因为第二个框仍在循环中。

我尝试将其置于循环之外,但没有成功,任何指针都可以很好地让 Else: MsgBox "所有位置正确输入" 显示一次!

Sub Scoring()
Dim FindString As String
Dim rng As Range
Dim startVal As Integer, endVal As Integer

startVal = 1
endVal = 9

For i = startVal To endVal
    FindString = CStr(i)
    With Sheets("Scoring").Range("S:S")
        Set rng = .Find(What:=FindString, _
                After:=.Cells(.Cells.Count), _
                LookIn:=xlValues, _
                LookAt:=xlWhole, _
                SearchOrder:=xlByRows, _
                SearchDirection:=xlNext, _
                MatchCase:=False)
        If Not rng Is Nothing Then
            MsgBox "There are one or more risks that do not contain the minimum       information required for import, please ammend these and try again.", True
            Exit For
        Else: MsgBox "All locations correctly entered"

       End If
    End With
 Next i

End Sub

【问题讨论】:

    标签: vba loops msgbox


    【解决方案1】:

    你可以引入一个布尔类型变量来存储truefalse。默认情况下,任何布尔变量都是 false,因此默认情况下 found 等于 false(您没有明确说 found = false,但它是可选的)。所以,你只需要在rng 不为空时将其值更改为true。在退出循环之前添加了found = true

    除非它是真的,否则它总是假的,这是合乎逻辑的。因此,当值匹配时,您可以切换变量状态。

    在宏代码的底部有一个额外的行来检查found 是否为false。如果是,那么将显示一个消息框而不是 10+。

    希望对你有帮助

    Sub Scoring()
    Dim FindString As String
    Dim rng As Range
    Dim startVal As Integer, endVal As Integer, i As Long
    
    startVal = 1
    endVal = 9
    
    Dim found As Boolean
    
    For i = startVal To endVal
        FindString = CStr(i)
        With Sheets("Scoring").Range("S:S")
            Set rng = .Find(What:=FindString, _
                    After:=.Cells(.Cells.Count), _
                    LookIn:=xlValues, _
                    LookAt:=xlWhole, _
                    SearchOrder:=xlByRows, _
                    SearchDirection:=xlNext, _
                    MatchCase:=False)
            If Not rng Is Nothing Then
                MsgBox "There are one or more risks that do not contain the minimum       information required for import, please ammend these and try again.", True
                found = True
                Exit For
           End If
        End With
     Next i
    
    If Not found Then MsgBox "All locations correctly entered"
    
    End Sub
    

    【讨论】:

      猜你喜欢
      • 2020-10-25
      • 1970-01-01
      • 1970-01-01
      • 2016-08-10
      • 2015-05-01
      • 1970-01-01
      • 2018-10-09
      • 1970-01-01
      • 2019-05-06
      相关资源
      最近更新 更多