首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >循环使用Excel中用户定义的范围。

循环使用Excel中用户定义的范围。
EN

Stack Overflow用户
提问于 2021-07-14 14:06:20
回答 2查看 99关注 0票数 0

我试图循环通过一个用户输入范围在一个子,以检查是否所有的值是数字。

如果值是数字的,则if语句总是会执行,并且这段代码进入无限循环。

另一个不太重要的问题是,错误捕获有一个退出子语句正在被忽略。

代码语言:javascript
运行
复制
Sub Select_Data_Validation_Range()
On Error GoTo ErrCatcher
    Dim Stage_Range As Range
    Dim cell As Range
    'This is where the user is propmeted to input the range
    Set Stage_Range = Application.InputBox("Please Select the apporiate range for the data validation", Type:=8)
        'This loop should be looping though each cell in the selected range
        For Each cell In Stage_Range
          'If the value in the cell is not a number then an error message should be given and the sub will be called again
          If IsNumeric(cell.Value) = False Then:
               MsgBox "The Range Can contain only numbers"
               Select_Data_Validation_Range
       Next cell
    Exit Sub

ErrCatcher:
    'Err.Number 424 occurs when some clicks the x buttom on the input box
    If Err.Number = 424 Then
        MsgBox "Thanks for using the sub", , "Exit"
        'After this error I want to exit the sub but instead the sub goes back to the for loop and continues that.
        Exit Sub
    'Tryig to catch all other errors to prevent the error window from popping up
    ElseIf Err.Number <> 424 Then
        MsgBox "Exited Sub with unknown error"
        'After this error I want to exit the sub but instead the sub goes back to the for loop and continues that.
        Exit Sub
    End If
End Sub

用户选择的范围应该是什么样子?

如果范围中有一个非数字值,应该发生什么?

EN

Stack Overflow用户

回答已采纳

发布于 2021-07-14 14:22:38

这不像你想的那样

代码语言:javascript
运行
复制
If IsNumeric(cell.Value) = False Then:
       MsgBox "The Range Can contain only numbers"
       Select_Data_Validation_Range

测试没有关闭If后面的行,因为:如果删除了:,就会得到一个"next无for“编译错误。

应该是这样的:

代码语言:javascript
运行
复制
If IsNumeric(cell.Value) = False Then
    MsgBox "The Range Can contain only numbers"
    Select_Data_Validation_Range
End If
票数 1
EN
查看全部 2 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/68379635

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档