Reputation: 5151
I am trying to delete all of the contents of certain named ranges under certain criteria. Specifically, if the name of the range ends in "CA", then all of the contents in the cells composing that range should be cleared. This is what I have so far:
For Each Nm in ActiveWorkbook.Names
If Right(Nm.Name, 2) = "CA" Then
Range(Nm.Name).ClearContents
End If
Next Nm
This produces an error:
Method 'Range' of object '_Global' failed
I've also tried to take off the .Name
and just use:
Range(Nm).ClearContents
but that gives the same error. Providing some sort of workbook and sheet reference gives the error:
Application-defined or object-defined error
Changing .ClearContents
to .Clear
does nothing.
I know it's finding the range because it's getting passed the if-statement
.
Am I missing something silly?
EDIT: For what it's worth, the named range in question is in another workbook from where the code is written that is opened in compatibility mode.
Upvotes: 1
Views: 12906
Reputation: 5151
So, I can't be sure why this happened as the workbook I was getting the named ranges from was not one I created, but it appears as though the "RefersTo" for the named ranges in question had extra quotation marks that needed to be removed so as to refer to a legitimate range. See below
So I added code that replaced the quotation marks with nothing and this seemed to have resolved the issue.
For Each Nm In Names
If Right(Nm.Name, 2) = "CA" Then
newName = Replace(CStr(Nm), Chr(34), "")
Range(newName).ClearContents
End If
Next Nm
I know many of you have been looking at this and I appreciate it. Thank you.
Upvotes: 2
Reputation: 10705
This works for me:
Dim nm As Name
For Each nm In Names
If LCase(Right(nm.Name, 2)) = "ca" Then
Range(nm).ClearContents
End If
Next nm
Upvotes: 0