Excel VBA: Can I name a range using a formula?

前端 未结 2 431
遇见更好的自我
遇见更好的自我 2021-01-27 10:59

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

2条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-01-27 11:32

    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.

提交回复
热议问题