Resize array vba excel

Свойство Resize объекта Range позволяет в коде VBA Excel изменять размер указанного диапазона. Синтаксис свойства Range.Resize, его параметры и примеры использования.

Свойство Range.Resize устанавливает новый размер исходного диапазона по указанному количеству строк и столбцов.

Синтаксис свойства Range.Resize

Expression.Resize(RowSize, ColumnSize)

Конструкция, представляющая синтаксис свойства, не может использоваться отдельно сама по себе, иначе VBA Excel сгенерирует ошибку. Поскольку свойство Range.Resize возвращает диапазон нового размера, его можно присвоить переменной или применить к нему какой-либо метод.

Параметры свойства Range.Resize

Параметр Описание
Expression Выражение, возвращающее исходный диапазон, которому требуется изменить размер. Тип данных параметра — Range.
RowSize Число строк или выражение, возвращающее количество строк нового диапазона. Тип данных параметра — Variant. Если этот аргумент пропущен, число строк в диапазоне останется прежним.
ColumnSize Число столбцов или выражение, возвращающее количество столбцов нового диапазона. Тип данных параметра — Variant. Если этот аргумент пропущен, число столбцов в диапазоне останется прежним.

Параметры RowSize и ColumnSize определяют именно количество строк и столбцов нового диапазона, а не количество добавляемых или вычитаемых из исходного диапазона. Значения аргументов RowSize и ColumnSize должны быть больше нуля, иначе VBA Excel сгенерирует ошибку.

Примеры использования в VBA Excel

Пример 1

Sub Primer1()

Dim a As Range

  Set a = Range(«C3:E5»)

  Set a = a.Resize(5, 5)

MsgBox a.Address

End Sub

В первом примере мы присваиваем переменной a диапазон из трех столбцов и трех строк, а затем преобразуем его с помощью кода VBA Excel в диапазон из пяти столбцов и пяти строк и перезаписываем его в ту же переменную a. Обратите внимание, что диапазон расширяется вправо (столбцы) и вниз (строки). При уменьшении диапазона, «лишние столбцы и строки» будут исключены из него, соответственно, справа и снизу.

Пример 2

Sub Primer2()

Dim a As Range

  Set a = Range(«A1:E5»)

  a.Resize(2, 2).Select

MsgBox a.Address

End Sub

Во втором примере мы уменьшили размер исходного диапазона и применили к нему метод Select. Обратите внимание, что уменьшенный диапазон выбран с помощью метода Select на активном листе рабочей книги Excel, а в переменной a диапазон остался прежним, что и покажет информационное окно MsgBox.

Пример 3

Sub Primer3()

Dim a As Range

  Set a = Union(Range(«A1:A5»), Range(«B1:B5»)).Resize(4, 4)

MsgBox a.Address

End Sub

В третьем примере кода VBA в качестве Expression свойства Range.Resize используется выражение с методом Union.


Return to VBA Code Examples

In this Article

  • Resize Range Using VBA
    • Syntax
    • Resize Number Of Rows And Columns
    • Resize Number Of Rows Only
    • Resize Number Of Columns Only
    • Resize Table Range To Exclude Header
    • Write 2-D Array To Range

Resize Range Using VBA

This tutorial will demonstrate how to use the Resize Property of the Range Object to change to return a new range resized from the original Range object.

Syntax

Syntax for the Resize property is:

Range("A1").Resize (RowSize, ColumnSize)

Where Range(“A1”) is your starting range.

RowSize and ColumnSize must be greater than zero. Each input is optional (ex. you can omit RowSize to only change the number of columns, or vice-versa).

Resize Number Of Rows And Columns

Following example expands the range with one cell A1 to range A1:D10 by increasing row count to 10 and columns count to 5.

Range("A1").Resize(10, 5).Select

vba resize range

Or, more commonly you’ll assign the resized range to a variable:

    ' Resize range to the desired size and assign to a variable
    Set newRng = ActiveSheet.Range("A1").Resize(10, 5)

Resize Number Of Rows Only

Following example changes the number of rows only:

    ' Change Row Size only, New Range will be $A$1:$A$10
    Set newRng = rng.Resize(10)

Resize Number Of Columns Only

Following example changes the number of columns only:

    ' Change Column Size only, new Range will be $A$1:$E$1
    Set newRng = rng.Resize(, 5)

If you have a table on active sheet with a header row, the code will first select the entire table then move down one row to exclude the header using Range.Offset method. It will then use the Range.Resize property to reduce the size by one row.

Sub SelectTableData()
    ' **IMPORTANT**
    ' Click on any cell of the table before running the macro
    
    ' Move down one row by using Offset and then reduce range size by one row
    Set tbl = ActiveCell.CurrentRegion.Offset(1, 0)
    Set tbl = tbl.Resize(tbl.Rows.Count - 1, tbl.Columns.Count)
     
    ' Data is selected excluding header row
    tbl.Select
End Sub

VBA Coding Made Easy

Stop searching for VBA code online. Learn more about AutoMacro — A VBA Code Builder that allows beginners to code procedures from scratch with minimal coding knowledge and with many time-saving features for all users!

automacro

Learn More

Write 2-D Array To Range

Another common usage is to write a 2 dimensional array to a sheet. Since the range to be written should match the size of the array, which is normally not known in advance, the Resize method is used to set the output range.

The xxample below will read the data in the range A1:E10 in active sheet to an array and write the array out to ‘Output’ sheet starting from cell A1:

Sub WriteArray()   
    ' Read the data to an array
    data = Range("A1:E10").Value
    ' Resize the output range and write the array
    Worksheets("Output").Range("A1").Resize(UBound(data, 1), UBound(data, 2)).Value = data
End Sub

Written by: Vinamra Chandra

# Populating arrays (adding values)

There are multiple ways to populate an array.

# Directly

# Using Array() function

# From range

# 2D with Evaluate()

# Using Split() function

# Dynamic Arrays (Array Resizing and Dynamic Handling)

Due to not being Excel-VBA exclusive contents this Example has been moved to VBA documentation.

Link:
Dynamic Arrays (Array Resizing and Dynamic Handling) (opens new window)

# Jagged Arrays (Arrays of Arrays)

Due to not being Excel-VBA exclusive contents this Example has been moved to VBA documentation.

Link:
Jagged Arrays (Arrays of Arrays) (opens new window)

# Check if Array is Initialized (If it contains elements or not).

A common problem might be trying to iterate over Array which has no values in it. For example:

To avoid this issue, and to check if an Array contains elements, use this oneliner:

# Dynamic Arrays [Array Declaration, Resizing]

The Excel VBA ReDim statement initializes and resizes a dynamic VBA Array. Be sure to check the difference between Fixed VBA Arrays and Dynamic VBA Arrays.

ReDim [Preserve] varname ( subscripts ) 

Parameters

Preserve
Optional. Keyword to be used if you want to resize your array and keep all items intact.
varname
The name of the array variable.
subscripts
The subscripts of the array defining either it’s upper bounds or lower and upper bounds. See examples below.

Using ReDim with single dimension arrays

Below an example of sizing and resizing a VBA Array:

Dim arr() As Variant 'declaration of variant array
ReDim arr(2) 'Sizing array to upper bound 2. Array size is 3 -> 0 to 2
arr(2) = 10
Debug.Print arr(2) 'Result: 10

ReDim arr(1 to 2) 'Resizing array to size 2 -> 1 to 2. All items will be empty again.
Debug.Print array(2) 'Result: Empty

Using ReDim to resize an array but preserving its contents

Below an example of sizing and resizing a VBA Array, but keeping its contents preserved:

Dim arr() As Variant 'declaration of variant array
ReDim arr(2) 'Sizing array to upper bound 2. Array size is 3 -> 0 to 2
arr(2) = 10
Debug.Print arr(2) 'Result: 10

ReDim Preserve arr(1 to 2) 'Resizing array to size 2 -> 1 to 2. All items will be Preserved as keyword was used.
Debug.Print array(2) 'Result: 10. Hurray!

Using ReDim with multidimensional arrays

Below an example of sizing and resizing a multidimensional array:

Dim arr() As Variant 'declaration of variant array
ReDim arr(2, 2)
arr(1, 1) = 10
    
ReDim Preserve arr(2, 10)
Debug.Print arr(1, 1) 'Result: 10


November 12, 2016/



Chris Newman

Dynamically Fill VBA Array Variables

What Are Arrays?

Arrays are a variant type variable that you can use in VBA coding to store a list of data. Think of it as a mini-spreadsheet inside of a single variable. You store data into an array by referring to a reference number that corresponds with the location that the piece of data is positioned in.

Below is an example of an array that is holding all the month names within a year. Notice that the reference number starts at zero instead of one.

You can also have multi-dimensional arrays. Below is a two-dimensional array that looks much like a typical spreadsheet is setup. You can create even more dimensions if you need to (ie think «Data Cube»), but in my experience two dimensions is the max that a typical person will ever need. 

Now that you’ve had a quick overview of what arrays are, let’s get into the meat of this article and learn various ways to dynamically resize these variables to fit all of your data.

Method 1: Resizing First

This method resizes the array to the size of your target data or list before actually placing the values inside the array. This can be a good option if you know beforehand how many items you need to store.

Sub PopulatingArrayVariable()
‘PURPOSE: Dynamically Create Array Variable based on a Given Size

Dim myArray() As Variant
Dim DataRange As Range
Dim cell As Range
Dim x As Long

‘Determine the data you want stored
  Set DataRange = ActiveSheet.UsedRange

‘Resize Array prior to loading data
  ReDim myArray(DataRange.Cells.Count)

‘Loop through each cell in Range and store value in Array
  For Each cell In DataRange.Cells
    myArray(x) = cell.Value
    x = x + 1
  Next cell

‘Print values to Immediate Window (Ctrl + G to view)
  For x = LBound(myArray) To UBound(myArray)
    Debug.Print myArray(x)
  Next x

End Sub

Method 2: Resizing As You Go

This VBA method resizes the array variable right before storing each item. The key command here is «Preserve«. This tells the code to keep all the stored items in the Array while increasing it’s storage capacity. If you forgo having Preserve in your code immediately after you ReDim, the array variable will wipe clean of data previously stored in it before re-dimensioning.

Sub PopulatingArrayVariable()
‘PURPOSE: Dynamically Create Array Variable based on a Given Size

Dim myArray() As Variant
Dim DataRange As Range
Dim cell As Range
Dim x As Long

‘Determine the data you want stored
  Set DataRange = ActiveSheet.UsedRange

‘Loop through each cell in Range and store value in Array
  For Each cell In DataRange.Cells
    ReDim Preserve myArray(x)
    myArray(x) = cell.Value
    x = x + 1
  Next cell

‘Print values to Immediate Window (Ctrl + G to view)
  For x = LBound(myArray) To UBound(myArray)
    Debug.Print myArray(x)
  Next x

End Sub

Method 3: Creating From A Delimited String

Another way you can populate an array variable is through a delimiter. A delimiter is simply a designated set of character(s) that separates out your values. Have you ever heard of a CSV file? CSV stands for «Comma-Separated Values» where a comma symbol tells your computer how to separate each value apart from one another.

You can use this same concept to make your own delimited string or (more realistically) read a delimited string exported from your database software to populate the array. In my below example code I am taking a set range and turning it into a delimited string with the characters «;|;» separating each value. 

Sub PopulatingArrayVariable()
‘PURPOSE: Dynamically Create Array Variable based on a Given Size

Dim myArray As Variant
Dim myString As String
Dim DataRange As Range
Dim cell As Range
Dim x As Long

‘Determine the data you want stored
  Set DataRange = ActiveSheet.Range(«A1:A100»)

‘Loop through each cell in Range and store value in delimited string
  For Each cell In DataRange.Cells
    myString = myString & «;|;» & cell.Value
  Next cell

‘Remove first delimiter from string (;|;)
  myString = Right(myString, Len(myString) — 3)

  ‘Create an array with the Split() function
  myArray = Split(myString, «;|;»)

‘Print values to Immediate Window (Ctrl + G to view)
  For x = LBound(myArray) To UBound(myArray)
    Debug.Print myArray(x)
  Next x

End Sub

If you are already starting with a delimited string, use this simplified VBA code to accomplish the same thing.

Sub PopulatingArrayVariable()
‘PURPOSE: Dynamically Create Array Variable based on a Given Size

Dim myArray As Variant
Dim myString As String
Dim x As Long

‘Store delimited string to a variable
  myString = «Apple;|;Orange;|;Pear;|;Peach;|;Grapes»

  ‘Create an array with the Split() function
  myArray = Split(myString, «;|;»)

‘Print values to Immediate Window (Ctrl + G to view)
  For x = LBound(myArray) To UBound(myArray)
    Debug.Print myArray(x)
  Next x

End Sub

Method 4: Pulling From An Excel Table [My Favorite Option!]

This is my favorite way to populate array variables dynamically because it has a user-interface aspect to it (ie it allows you to make changes to the inputs without rewriting the code). Now you may be thinking to yourself that a couple of the VBA snippets above are pulling from ranges that you could easily substitute with a named range in your code. This is true, but tables have the auto-expanding feature that can make you 100% certain from a visual perspective that you are picking up all your values.

You will want to note that when you size an Array variable from a Range or Table, the first reference number will be a One instead of the typical Zero.

Sub PopulatingArrayVariable()
‘PURPOSE: Dynamically Create Array Variable based on a Single Columned Table

Dim myArray() As Variant
Dim TempArray() As Variant
Dim myTable As ListObject
Dim x As Long

‘Set path for Table variable
  Set myTable = ActiveSheet.ListObjects(«Table1»)

  ‘Create Array List from Table
  TempArray = myTable.DataBodyRange.Columns(1)

  ‘Convert from vertical to horizontal array list
  myArray = Application.Transpose(TempArray)

‘Loop through each item in the Table Array (displayed in Immediate Window [ctrl + g])
  For x = LBound(myArray) To UBound(myArray)
    Debug.Print myArray(x)
  Next x

End Sub

Any Other Methods?

Are there any other methods you use to populate arrays dynamically? I would love to hear from you in the comments section below and maybe I can add some other options to the ones I’ve already discussed in the article.

About The Author

Hey there! I’m Chris and I run TheSpreadsheetGuru website in my spare time. By day, I’m actually a finance professional who relies on Microsoft Excel quite heavily in the corporate world. I love taking the things I learn in the “real world” and sharing them with everyone here on this site so that you too can become a spreadsheet guru at your company.

Through my years in the corporate world, I’ve been able to pick up on opportunities to make working with Excel better and have built a variety of Excel add-ins, from inserting tickmark symbols to automating copy/pasting from Excel to PowerPoint. If you’d like to keep up to date with the latest Excel news and directly get emailed the most meaningful Excel tips I’ve learned over the years, you can sign up for my free newsletters. I hope I was able to provide you with some value today and I hope to see you back here soon!

— Chris
Founder, TheSpreadsheetGuru.com

VBA Range to 2D Array

These list of topics are covered in this page.

  1. Vba Code to initialize 2D Array with Range
  2. Vba to write Array data to worksheet
  3. Resize Array to fit worksheet.

This code converts worksheet data in specific range into an vba array. Lets see how it works.

1.Excel Macro – Convert Range To Array(2-Dimention)

Actually, it does not require any special function. It is almost easy like assigning a value to a variable.

Once you assign the range to the array, Excel automatically calculates & allocates array dimensions. You don’t have to specify the number of rows, columns or dimensions for the array.

Excel decides these parameters automatically & created a 2D Array by default. It will be clear from below example.

'--------------------------------------------------------------------------------
'Visit https://officetricks.com to get more Free & Fully Functional VBA Codes
'--------------------------------------------------------------------------------
Sub Range_To_Array()
    'Declare Array as variant & Range
    Dim rArray() As Variant, rRange As Range, iRow As Double, iCol As Double
    
    'Initialize Range to Reference a portion of Worksheet
    Set rRange = ThisWorkbook.Sheets("sheet1").Range("A1:D2")
    
    'Assign Range to Array
    rArray = rRange.Value
    
    'Read content of Array one by one
    For iRow = 1 To UBound(rArray, 1)
        For iCol = 1 To UBound(rArray, 2)
            Debug.Print rArray(iRow, iCol)
        Next
    Next           
End Sub

Once you convert the worksheet data to array, you get the advantage of using the Array function on the values. This way the code runs much faster than accessing worksheet data each time.

2. Convert Array to Range – Write to Worksheet

When we write values back to worksheet from array, you have to explicitly mention number of rows & columns the data should occupy.

For this first assign a cell to a range variable: set rng = Thisworkbook.Sheet(1).Range(“A1”) & then use range.resize as explained in this code.

Sub ArrayToRange()
    'Declare Array as variant & Range
    Dim rArray() As Variant, rRange As Range, iRow As Double, iCol As Double
    Set rRange = ThisWorkbook.Sheets("sheet1").Range("A1:D2")
    rArray = rRange.Value
    
           
    'Write values in Array back To a Range in worksheet
    Set rRange = ThisWorkbook.Sheets("sheet1").Range("F1:I2")
    rRange = rArray
    
    'OR Resize Range as per the structure of Array
    iRow = UBound(rArray, 1)
    iCol = UBound(rArray, 2)
    Set rRange = ThisWorkbook.Sheets("sheet1").Range("F1")
    Set rRange = rRange.Resize(iRow, iCol)
    MsgBox rRange.Address(0, 0)
    rRange = rArray
End Sub

To know how Range.resize works, read further in the next section.

3. Excel VBA – Resize Array to fit Worksheet

Once it is initialized, then it can be extended or resized as per the structure of the array.

'Get Number of Rows in Array
rows = UBound(arr,1)

'Get number of columns in Array
cols = UBound(arr,2)

'Resize array as per the array dimensions
set rng = rng.resize(rows,cols)

'Write Array value to the Range
rng = arr

So, the Excel VBA function Range.Resize holds the key here. It can be used to expand or compress the target destination range size.

I have often read that processing values from an array is much faster than processing values from Excel sheet. Though, I haven’t tested this. But, in case you want to move the values from worksheet or Table to an Array, then this code can be used.

External Reference: Here is another wonderful article from cpearson about arrays & worksheets.

Понравилась статья? Поделить с друзьями:
  • Resident of this word
  • Resetted is not a word
  • Reserved word in java
  • Reservations meaning of the word
  • Research word derived from