Excel

Sort and adjust named range when data is inserted, deleted or changed.

Ease of Use

Easy

Version tested with

2000, 2003 

Submitted by:

mdmackillop

Description:

The code re-sorts a named range when data is added, deleted or changed, and applies the range name to the re-dimensiond range. 

Discussion:

Automatically maintain a sorted named range. Useful for data validation source and other purposes. 

Code:

instructions for use

			

Option Explicit Private Sub Worksheet_Change(ByVal Target As Range) Dim MyData As String Dim OldData As Range Dim NewData As Range Dim Nms, r As Long 'Determine rangename containing target Set Nms = ActiveWorkbook.Names For r = 1 To Nms.Count If Not Intersect(Target, Range(Nms(r))) Is Nothing Or _ Not Intersect(Target.Offset(-1), Range(Nms(r))) Is Nothing Then MyData = Nms(r).Name Exit For End If Next Set OldData = Range(MyData) 'Check if target is in existing range or cell below If Not Intersect(Target, OldData) Is Nothing Then Set NewData = OldData 'In existing range ElseIf Not Intersect(Target, OldData.Offset(1)) Is Nothing Then Set NewData = Union(OldData, OldData.Offset(1)) 'Below existing range Else Exit Sub 'Not in data region End If 'Sort Data NewData.Sort Key1:=NewData.Cells(1), Order1:=xlAscending, Header:=xlNo, _ OrderCustom:=1, MatchCase:=False, Orientation:=xlTopToBottom 'Reset range name ActiveWorkbook.Names.Add Name:=MyData, RefersTo:="=" & ActiveSheet.Name & "!" & _ Range(NewData.Cells(1), NewData.Cells(1).End(xlDown)).AddressLocal 'For demo purposes **************** Range(MyData).Interior.ColorIndex = 6 MsgBox "Range " & MyData Range(MyData).Interior.ColorIndex = xlNone '********************************** Set Nms = Nothing Set OldData = Nothing Set NewData = Nothing End Sub

How to use:

  1. Open an Excel workbook
  2. Select Tools/Macro/Visual Basic Editor
  3. In the VBE window, select Tools/Project Explorer
  4. Select the a Worksheet module module
  5. Copy and paste the code above into the Module
  6. Rename the RangeName as required
  7. Now select File/Close and Return To Microsoft Excel
  8. Set the RangeName in the spreadsheet
  9. Save the file.
 

Test the code:

  1. Open the sample file
  2. Delete or change data in the column
  3. Add data to the bottom of the column
  4. In sample file only, the named range will be coloured yellow as it changes.
 

Sample File:

DynamicRange.zip 9.43KB 

Approved by mdmackillop


This entry has been viewed 359 times.

Please read our Legal Information and Privacy Policy
Copyright @2004 - 2020 VBA Express