【问题标题】:Evaluated range with `Int` function when range contains non integer values当范围包含非整数值时,使用“Int”函数评估范围
【发布时间】:2018-07-26 13:46:39
【问题描述】:

我希望我的循环评估一个范围内的值,如果该值非零且为整数,则继续。我的范围还包含字母数字值,我希望忽略这些值。

当我点击其中一个字母数字值时,我的循环卡住了。我该如何解决?

我的代码:

Dim r2 As Range
Dim fnd As Range
Dim Answer3 As String
    For Each r2 In WorkRng2
        If r2.Value <> "" And WorksheetFunction.IsNumber(r2.Value) Then
            If r2.Value = Int(r2.Value) Then
            Set fnd = WorkRng1.Find(what:=r2.Value, LookIn:=xlValues)
                If fnd Is Nothing Then
                'nothing found
                Answer3 = MsgBox("Cannot proceed! Major Task " & r2.Value & " could not be found in invoice review file!", vbOKOnly, "Question!")
                    If Answer3 = vbOK Then
                        Exit Sub
                    Else
                    'fnd holds the cell that was found
                    End If
                End If
            End If
        End If
    Next

另外,WorkRng1WorkRng2 是公共变量

【问题讨论】:

  • 您需要两个IF...。首先检查非空白和数字(If r2.Value &lt;&gt; "" And WorksheetFunction.IsNumber(r2.Value)).,然后检查数字是否为 int(If r2.Value = Int(r2.Value)...)
  • @AlexP 我做对了吗?我做了大编辑。当我运行代码时,我没有得到预期的结果,它似乎会继续运行而不会停止并显示消息框
  • 在该行放一个断点并调试并查看跳过 MsgBox 时fnd 的值。
  • @JacobH 我添加了LookAt:=xlWhole 并将两个范围的格式转换为文本,现在可以使用了。感谢您的帮助

标签: excel loops if-statement vba


【解决方案1】:

对于那些想知道我如何在 cmets 的帮助下解决问题的人,这里是我的工作代码:

Application.ScreenUpdating = False
    WorkRng1.NumberFormat = "@"
    WorkRng2.Parent.Activate
    WorkRng2.NumberFormat = "@"
    WorkRng1.Parent.Activate
Application.ScreenUpdating = True
Dim r2 As Range
Dim fnd As Range
Dim Answer3 As String
    For Each r2 In WorkRng2
        If r2.Value <> "" And WorksheetFunction.IsNumber(r2.Value) Then
            If r2.Value = Int(r2.Value) And r2.Value <> "9" Then
            Set fnd = WorkRng1.Find(what:=r2.Value, LookIn:=xlValues, LookAt:=xlWhole)
                If fnd Is Nothing Then
                'nothing found
                Answer3 = MsgBox("Cannot proceed! Major Task '" & r2.Value & "' could not be found in invoice review file!", vbOKOnly, "Question!")
                    If Answer3 = vbOK Then
                        Exit Sub
                    Else
                    'fnd holds the cell that was found
                    End If
                End If
            End If
        End If
    Next
Application.ScreenUpdating = False
    WorkRng1.NumberFormat = "0.0"
    WorkRng2.Parent.Activate
    WorkRng2.NumberFormat = "0.0"
    WorkRng1.Parent.Activate
Application.ScreenUpdating = True

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-03
    • 1970-01-01
    • 1970-01-01
    • 2019-11-11
    • 1970-01-01
    相关资源
    最近更新 更多