My goal is to name my just-pasted range something unique to I can find it in the future.
The copied and pasted range comes from a drop-down menu, and thus must be modi
I believe what you are trying to do is:
Selection.Name = "AddSection_" & Replace(Worksheets("Add Section").Range("D3").Value, " ", "")
or, setting it up to ensure that the range name has not yet been used, perhaps something like:
Dim myName As String
Dim maxSuffix As Long
Dim n As Name
myName = "AddSection_" & Replace(Worksheets("Add Section").Range("D3").Value, " ", "")
maxSuffix = 0
For Each n In Names
If Left(n.Name, Len(myName)) = myName Then
If IsNumeric(Mid(n.Name, Len(myName) + 1)) Then
If CLng(Mid(n.Name, Len(myName) + 1)) > maxSuffix Then
maxSuffix = CLng(Mid(n.Name, Len(myName) + 1))
End If
End If
End If
Next
Selection.Name = myName & (maxSuffix + 1)
This only increments the count if the existing base name has been used before, i.e. AddSection_OilFurnace1
, then AddSection_OilFurnace2
, then maybe AddSection_GasFurnace1
- it doesn't go AddSection_OilFurnace1
, AddSection_GasFurnace2
, AddSection_OilFurnace3
- but maybe it is useful.
I think YowE3K has the right approach. I refactored his code because I don't like Do Loop
.
Sub AddName()
Dim myNameBase As String
Dim arr() As String
Dim maxName As Long
Dim n As Name
myNameBase = "AddSection_" & Replace(Worksheets("Add Section").Range("D3").Value, " ", "")
For Each n In Names
If n.Name Like myNameBase & "*" Then
If n.Name = myNameBase Then
maxName = 1
ElseIf n.Name Like myNameBase & ".*." Then
arr = Split(n.Name, ".")
If arr(UBound(arr) - 1) >= maxName Then maxName = arr(UBound(arr) - 1) + 1
End If
End If
Next
Selection.Name = myNameBase & IIf(maxName, "." & maxName & ".", "")
End Sub
YowE3K Thanks for the help!