View Single Post
  #1   Report Post  
Posted to microsoft.public.excel.programming
Patrick Molloy[_2_] Patrick Molloy[_2_] is offline
external usenet poster
 
Posts: 1,298
Default Automatically Defining Ranges

try this

Option Explicit

Sub AddAutoName()

Dim firstrow As Long
Dim lastrow As Long
Dim text As String

With Worksheets("Sheet1")
firstrow = 1
Do
text = .Cells(firstrow, 1)
lastrow = firstrow
Do While .Cells(lastrow + 1, 1) = text
lastrow = lastrow + 1
Loop
.Range(.Cells(firstrow, 1), .Cells(lastrow, 7)).Name = text
firstrow = lastrow + 1
Loop Until .Cells(firstrow, 1) = ""
End With
End Sub

If your values in colun=mn a are cghanging, then befor ethey change, it
might be useful to remove range names if they're no needed. The AutoName proc
will add any that are required again.

Sub RemoveAutoName()
Dim rw As Long
On Error Resume Next
With Worksheets("Sheet1")
rw = 1
Do
Names.Item(.Cells(rw, 1).Value).Delete
rw = rw + 1
Loop Until .Cells(rw, 1) = ""
End With
On Error GoTo 0
End Sub






" wrote:

I have data that is going to change every month, and need a code that I
can use to define ranges automatically within that data. There will be
some months where certain codes are in the data, and other months where
it won't be there. So I likely would need to run the macro every
month. I will present an example:

The data will have seven columns, and will be sorted by column A, which
contains the codes needed to define the ranges:

Example:

Column A
ABEHS
ABEHS
ABEHS
ABEHS
BOOOT
BOOOT
BOOOT
CAHGT
CAHGT
DOORT

So what I would need the VBA code to do is define the first four rows
as a defined range called "ABEHS", the next 3 to be defined as "BOOOT",
etc. Remember, the data changes every month - so next month, the
first 10 rows may be ABEHS...or perhaps I will have no ABEHS data at
all.