Home » excel » excel – Search for names in name manager and set values

excel – Search for names in name manager and set values

Posted by: admin May 14, 2020 Leave a comment

Questions:

I have a lot of named ranges. They all are like MFiles_PG9317B4DE414D4DE3A781648B8F8B5C2Fn1_ID. Common thing to all of them is that they all start with MFiles_. Time to times I need to set their values to "". Clicking each one and setting value manually is one of a job. I would like to do it by code. I guess I have to loop through all of them, search for names starting with MFiles_ and set their value to "". How to do that?

Note! Named ranges should stay as they are, only values should be set to "". So MFiles_PG9317B4DE414D4DE3A781648B8F8B5C2Fn1_ID with value (for example) =78324 after code run should be "" but name should stay untouched MFiles_PG9317B4DE414D4DE3A781648B8F8B5C2Fn1_ID. Also all the others begging with MFiles_

Sub NamedRange_Loop()

Dim nm As Name

'Loop through each named range in workbook
  For Each nm In ThisWorkbook.Names
    If nm = MFiles_ Then
       Name.Value =""
    End If
  Next nm

End Sub

EDIT:

Mikku’s solution gives:
enter image description here

How to&Answers:

Very close 🙂

Sub NamedRange_Loop()

Dim nm As Name

'Loop through each named range in workbook
  For Each nm In ThisWorkbook.Names
    If InStr(1, nm.Name, "MFiles_") Then
       nm.RefersTo = "=""""" 'nm.Value = "=""""" does the same thing
    End If
  Next nm

End Sub

Answer:

Something Like this:

Sub NamedRange_Loop()

Dim nm As Name

  For Each nm In ThisWorkbook.Names

       If Left(nm.Name, 7) = "MFiles_" Then

         Range(nm).Value = ""

       End If

  Next nm

End Sub

If you will use nm.Value = "" it will delete the Named Ranges. But if you use Range(nm).Value = "" it will retain the Named Ranges as it is.

enter image description here