testingVBA中是否存在范围

我在我的Excel中有一个dynamic定义的命名范围,从表中抓取基于开始date和结束date的数据

=OFFSET(Time!$A$1,IFERROR(MATCH(Date_Range_Start,AllDates,0)-1,MATCH(Date_Range_Start,AllDates)),1,MATCH(Date_Range_End,AllDates)-IFERROR(MATCH(Date_Range_Start,AllDates,0)-1,MATCH(Date_Range_Start,AllDates)),4) 

但是,如果date范围在表格中没有数据,则范围不存在(或某物,idk)。 如何在VBA中编写代码来testing这个范围是否存在?

我试过类似的东西

 If Not Range("DateRangeData") Is Nothing Then 

但我得到“运行时错误1004,对象'_Global'的方法'范围'失败。

你可以复制你的VBA中的匹配数,然后使用你需要的行数,或者你可以使用error handling:

 On Error Resume Next Debug.Print range("DateRangeData").Rows.Count If Err = 1004 Then MsgBox "Range Empty" Exit Sub Else MsgBox "Range full" End If Err.Clear On Error GoTo 0 

这里是一个函数,我敲回来是否存在一个命名的范围。 它可能会帮助你。

 Function RangeExists(R As String) As Boolean Dim Test As Range On Error Resume Next Set Test = ActiveSheet.Range(R) RangeExists = Err.Number = 0 End Function 

这是另一种方法。 采取容器和你想testing的名字是有好处的。 这意味着您可以testing表格名称或工作簿名称。

喜欢这个:

 If NamedRangeExists(ActiveSheet.Names, "Date") Then ... Else ... End If 

要么

 If NamedRangeExists(ActiveWorkbook.Names, "Date") Then ... Else ... End If 

 Public Function NamedRangeExists(ByRef Container As Object, item As String) As Boolean Dim obj As Object Dim value As Variant On Error GoTo NamedRangeExistsError: value = Container(item) If Not InStr(1, CStr(value), "#REF!") > 0 Then NamedRangeExists = True End If Exit Function Exit Function NamedRangeExistsError: NamedRangeExists = False End Function 

根据你正在做的应用程序,最好考虑使用字典。 当你想检查是否存在某些东西时,它们特别有用。 以这个例子:

 Dim dictNames as Scripting.Dictionary Sub CheckRangeWithDictionary() Dim nm As Name 'Initially, check whether names dictionary has already been created If Not dictNames Is Nothing Then 'if so, dictNames is set to nothing Set dictNames = Nothing End If 'Set to new dictionary and set compare mode to text Set dictNames = New Scripting.Dictionary dictNames.CompareMode = TextCompare 'For each Named Range For Each nm In ThisWorkbook.Names 'Check if it refers to an existing cell (bad references point to "#REF!" errors) If Not (Strings.Right(nm.RefersTo, 5) = "#REF!") Then 'Only in that case, create a Dictionary entry 'The key will be the name of the range and the item will be the address, worksheet included dictNames(nm.Name) = nm.RefersTo End If Next 'You now have a dictionary of valid named ranges that can be checked End Sub 

在你的主要程序中,你所需要做的就是在使用范围之前做一个存在检查

 Sub CopyRange_MyRange() CheckRangeWithDictionary If dictNames.exists("MyRange") then Sheets(1).Range("MyRange").Copy end if End Sub 

加载字典可能看起来更长一些,但处理和search速度非常快。 检查是否存在任何指向有效地址的命名范围,而不使用此简单应用程序中的error handling程序也变得更加简单。

请注意,当在表级别而不是工作级别使用名称时,需要使用更精细的密钥来保证唯一性。 从创build字典的方式来看,如果重复键,则项目值被覆盖。 这可以通过使用相同的Exists方法作为密钥创build语句中的检查来避免。 如果你需要一个关于如何使用字典的很好的参考,请使用这个。

祝你好运!