【问题标题】:Check if couple of ranges are met in worksheet [duplicate]检查工作表中是否满足几个范围[重复]
【发布时间】:2015-09-16 10:27:04
【问题描述】:

我有如下代码,我想检查工作表中是否满足一组命名范围,如果是,则执行某些操作,但是当 if 行中不满足范围时收到错误,如何解决?谢谢

If Range("Range1") Is Nothing Or Range("Range2") Is Nothing Or Range("Range3") Is Nothing Or Range("Range4") Is Nothing Or Range("Range5") Is Nothing Then

MsgBox "Check if in file each of required range is mentioned!"
Else
'do something
End if

【问题讨论】:

  • 你收到什么样的错误?
  • 运行时错误 '1004' 对象 '_Global' 的方法 'Range' 失败
  • 所有范围都定义了吗?您指的是"Range1","Range2" 等,但是这些命名范围是否已定义?如果你没有设置那些命名范围Excel会抛出一个错误。
  • 其中一个可能未定义,我想检查它是否已定义

标签: vba excel


【解决方案1】:

其中一种方法是检查.Name 是否与您定义的命名Range 匹配,并使用Integer 计数器来匹配Ranges 的数量。

见下面的代码:

Private Sub CheckNamedRanges()

    Dim nm As Name
    Dim wb As Workbook
    Dim i As Integer

    Set wb = ActiveWorkbook

    For Each nm In wb.Names
        If nm.Name = "Range1" Or nm.Name = "Range2" Or nm.Name = "Range3" Or nm.Name = "Range4" Or nm.Name = "Range5" Then
            i = i + 1
        End If
    Next

    If i = 5 Then
        'do something
    Else
        MsgBox "Check if in file each of required range is mentioned!"
    End If
End Sub

(请注意,我不是 100% 确定这是最有效的方法)

【讨论】:

    【解决方案2】:

    试试这样的

    Sub CheckTheRange()
    Dim CheckMyRange As Range
    
    On Error Resume Next
    Set CheckMyRange = Range("MyRange")
    On Error GoTo 0
    If CheckMyRange Is Nothing Then
         'Error, range not found
    Else
         'Go for it
    End If
    
    End Sub
    

    【讨论】:

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