2

I'm having an issue which appears to be simple, but I can't figure out what's the problem with my code.

Dim x As Long, y As Long, z As Long
Dim ContractName As String
Dim RangeToName As Range

y = Cells(1, 1).End(xlToRight).Column

    For x = 1 To y
        ContractName = Cells(1, x)
        z = Cells(Rows.count, x).End(xlUp).Row
        Set RangeToName = Range(Cells(2, x), Cells(z, x))
        RangeToName.Name = ContractName
    Next x
End Sub

I'm trying to name ranges based on the text in the "ContractName" cell which will change for each x.

But the line "RangeToName.Name = ContractName" gives me a run-time 450 error.

However if I add any other text in that line for example "RangeToName.Name = "test" & ContractName" everything works and my ranges are named with the full string of text including the text in the "ContractName" cell...

What am I missing?

Cheers

6
  • Have you tried ContractName = Cells(1,x).Value or ContractName = Cells(1,x).Text ? Commented Mar 17, 2015 at 11:53
  • 1
    @RubberDuck Hi, yes both give me the same 450 error. Commented Mar 17, 2015 at 11:57
  • @pnuts Hi, I'm trying to name each successive range (RangeToName) with the specific text present in the first cell above each column (ContractName). Commented Mar 17, 2015 at 12:00
  • 4
    A name must begin with a letter or underscore, does not contain spaces and must not be the same as a reserved keyword in Excel. In other words: A name can't begin with a digit. Commented Mar 17, 2015 at 12:00
  • 1
    @AxelRichter sounds like you should post that as an answer. Commented Mar 17, 2015 at 12:10

1 Answer 1

3

A name must begin with a letter or underscore, may not contain spaces, and must not be the same as a reserved keyword in Excel.

For example:

A name cannot begin with a digit.

A name cannot be "This is a test"

A name cannot be "A1"

"KL2000" is not usable as a name because would be in conflict with the cell reference KL2000, but "_KL2000" would be usable.

You should always attempt what you're trying to do with VBA directly in the Excel Application. If you had done this with a name like "KL2000", you would have gotten a meaningful error message.

Sign up to request clarification or add additional context in comments.

1 Comment

Good information on this subject at Excel Names -- Named Ranges.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.