I am trying to set the first 7 characters of the first cell in a range to be a named ranges name IF the cell begins with the word "kit".
Here is what I have so far:
Sub DefineRanges()
Dim rngStart As Range
Set rngStart = Range("A1")
Dim LastRow As Integer
Dim RangeName As String
For Each cell In Range("A2:A7")
If LCase(Left(cell.Value, 3)) = "kit" Then
RangeName = LCase(Left(cell.Value, 7))
ActiveWorkbook.Names.Add _
Name:=RangeName, _
RefersToLocal:=Range(rngStart.Address & ":C" & cell.Row - 1)
Set rngStart = Range("A" & cell.Row)
End If
LastRow = cell.Row
Next
RangeName = LCase(Left(cell.Value, 7))
ActiveWorkbook.Names.Add _
Name:=RangeName, _
RefersToLocal:=Range(rngStart.Address & ":C" & LastRow)
End Sub
Essentially I want it to look through my overall Range, find any cells that begin with the word "kit", create a named range that goes from that cell until the next cell that begins with "kit", and assign the first 7 characters of that cell to be the ranges name. So far I am able to get it to create the ranges, but I run into issues when I try to pass the contents of the cell into the range name. Any ideas?
cell
outside the loop this is why the error. – Scott CranerActiveSheet
isn't the expected/intended worksheet, and if the names are already defined. And withoutOption Explicit
specified you'll quickly run into other problems, harder to diagnose. Always useOption Explicit
. – Mathieu Guindon