Excel

Create Dynamic Ranges

Ease of Use

Easy

Version tested with

2007 

Submitted by:

mdmackillop

Description:

A simple userform to assist in the creation of Dynamic Ranges using the Offset formula. 

Discussion:

Dynamic Ranges are required in many VBA routines. This userform should assist the beginner in quickly creating and checking these. 

Code:

instructions for use

			

Option Explicit Private Sub UserForm_Initialize() RefEditCell = ActiveSheet.Name & "!$A$1" RefEditCol = ActiveSheet.Name & "!$A:$A" End Sub Private Sub cmdCreate_Click() CreateFormula ActiveWorkbook.Names.Add Name:=txtRangeName, RefersTo:=lblRangeFormula.Caption End Sub Private Sub cmdDelete_Click() On Error GoTo Exits Range(txtRangeName)(1).Select DelName txtRangeName Exits: End Sub Private Sub cmdRangeSelect_Click() Range(txtRangeName).Select End Sub Private Sub CreateFormula() Dim txt1 As String Dim txt2 As String Dim txt3 As String Dim txt4 As String txt1 = "=OFFSET(" & RefEditCell & "," & txtRowOffset & "," & txtColOffset & "," txt2 = "COUNTA(" & RefEditCol & ")" Select Case txtAdjust Case Is < 0 txt3 = txtAdjust & "," Case 0 txt3 = "," Case Is > 0 If Left(txtAdjust, 1) = "+" Then txt3 = txtAdjust & "," Else txt3 = "+" & txtAdjust & "," End If End Select txt4 = txtCols & ")" lblRangeFormula.Caption = txt1 & txt2 & txt3 & txt4 End Sub Private Sub RefEditCell_Change() Dim Sht As String Dim Col As Long Sht = Split(RefEditCell, "!")(0) Col = Range(RefEditCell).Column RefEditCol = Sht & "!" & Sheets(Sht).Columns(Col).AddressLocal CreateFormula End Sub

How to use:

  1. Enter desired name for the range.
  2. Use the RefEdit boxes to select the reference cell and column which defines the number of cells.
  3. Set the Row and Column offsets and desired numbers of columns using the text boxes.
  4. Resize the range if required using the Adjust +/- textbox.
  5. Click the Create button to create range; click select to check the result.
  6. Click Delete to delete the range name if not required.
 

Test the code:

  1. The Vertical example is for the more usual Columns range, and Horizontal where a dynamic Rows range is required.
 

Sample File:

Dynamic.zip 23.49KB 

Approved by Jacob Hilderbrand


This entry has been viewed 917 times.

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