Vba excel union range

Определение блока ячеек, состоящего из объединения двух и более диапазонов, с помощью метода Application.Union из кода VBA Excel. Примеры объединения.

Описание

Application.Union – это метод VBA Excel, который возвращает объект Range, являющийся объединением двух или более указанных диапазонов.

Синтаксис

Application.Union (Arg1, Arg2, Arg3, ..., Arg30)

  • Arg1, Arg2 – обязательные аргументы, представляющие из себя диапазоны ячеек (объекты Range).
  • Arg3, …, Arg30* – необязательные аргументы, представляющие из себя диапазоны ячеек (объекты Range).

* Допустимо использование до 30 аргументов включительно.

Примеры

Пример 1
Объединение диапазонов, занимающих прямоугольную область:

Sub Primer1()

Dim rngun As Range, arg1 As Range, arg2 As Range, arg3 As Range

    Set arg1 = Range(«B2:D6»)

    Set arg2 = Range(«D2:F6»)

    Set arg3 = Range(«B5:F9»)

    Set rngun = Application.Union(arg1, arg2, arg3)

MsgBox «Адрес объединенного диапазона: « & rngun.Address

End Sub

Объединение диапазонов, занимающих прямоугольную область

Объединение диапазонов, занимающих прямоугольную область

Пример 2
Объединение несмежных диапазонов:

Sub Primer2()

Dim rngun As Range, arg1 As Range, arg2 As Range, arg3 As Range

    Set arg1 = Range(«B2:C4»)

    Set arg2 = Range(«E2:F5»)

    Set arg3 = Range(«C7:E9»)

    Set rngun = Application.Union(arg1, arg2, arg3)

MsgBox «Адрес объединенного диапазона: « & rngun.Address

End Sub

Объединение несмежных диапазонов

Объединение несмежных диапазонов

Пример 3
Объединение пересекающихся диапазонов:

Sub Primer3()

Dim rngun As Range, arg1 As Range, arg2 As Range, arg3 As Range

    Set arg1 = Range(«B2:E5»)

    Set arg2 = Range(«C3:F9»)

    Set arg3 = Range(«D4:D10»)

    Set rngun = Application.Union(arg1, arg2, arg3)

MsgBox «Адрес объединенного диапазона: « & rngun.Address

End Sub

Объединение пересекающихся диапазонов

Объединение пересекающихся диапазонов

Самый наглядный вариант объединения ячеек рассмотрен в первом примере, когда объединяемые диапазоны образуют одну прямоугольную область. Во втором и третьем примерах результат объединения аналогичен использованию свойства Range объекта Worksheet:

Set rngun = Range(arg1.Address & «, « & arg2.Address & «, « & arg3.Address)

Excel VBA Union

Union in VBA is similar to the union in other programming languages, in VBA we use union to combine two or more than two ranges to perform different sets of operations on them, the statement used for this is itself union and it is called as union method, for example, union(Range(B2:C7),Range(D2:E7)).select and this method will select the cells.

Union method performs the task of creating a union of two or more ranges and returns the result as a RANGE object. This works exactly the same as the below example with VBA RANGE objectRange is a property in VBA that helps specify a particular cell, a range of cells, a row, a column, or a three-dimensional range. In the context of the Excel worksheet, the VBA range object includes a single cell or multiple cells spread across various rows and columns.read more.

Table of contents
  • Excel VBA Union
    • Syntax
    • How to use the VBA Union Method to Join Multiple Range?
      • Example #1
      • Example #2 – Use Variables to Store Range of Cells
    • Error with Union Function
    • Recommended Articles

VBA Union

You are free to use this image on your website, templates, etc, Please provide us with an attribution linkArticle Link to be Hyperlinked
For eg:
Source: VBA Union (wallstreetmojo.com)

Syntax

Now take a look at the syntax of the UNION method.

VBA Union formula 1

We need to supply a minimum of 2 ranges.

  • Arg 1: This is the first range of cells we need to create the union of.
  • Arg 2: This is the second range of cells we need to create a union of.

First two parameters are mandatory, after mentioning two range of cells, then all the other arguments become optional.

When the data is scattered in pieces in cells, we need to combine together all the data range to one to perform a common task. We can create a union of scattered range to one to perform a similar task for all the union ranges.

To select multiple ranges of cells, we can usually use RANGE object. For example, if we want to select the range of cells from A1 to B5 and from B3 to D5, we can write the VBA codeVBA code refers to a set of instructions written by the user in the Visual Basic Applications programming language on a Visual Basic Editor (VBE) to perform a specific task.read more like below.

Code:

Sub Union_Example1()

  Union(Range("A1:B5"), Range("B3:D5")).Select

End Sub

This would select the range of cells like the below image.

VBA Union Example 1

As we can see in the above image first range is selected from A1 to B5, and the second range is selected from B3 to D5.

This is the common technique we all have used while coding. However, this is not the only method we have in coding in VBA; we can also use one more method called “union” to create a union of two or more ranges.

How to use the VBA Union Method to Join Multiple Range?

You can download this VBA Union Excel Template here – VBA Union Excel Template

Example #1

Let’s perform the same take as we did in the above example but this time by using the UNION method.

Step 1 – Open UNION function in the subprocedure.

Code:

Sub Union_Example1()

  Union(

End Sub

VBA Union Example 1-1

Step 2 – Mention the first range of cells using RANGE object. In this case, I am mentioning the first range of cells as A1 to B5.

Code:

Sub Union_Example1()

  Union(Range("A1:A5"),

End Sub

VBA Union Example 1-2

Step 3 – Now mention the second range of cells using RANGE object, in this case, I am mentioning the range of cells as B3 to D5.

Code:

Sub Union_Example1()

  Union(Range("A1:A5"),Range("B3:B5"))

End Sub

VBA Union Example 1-3

Step 4 – After creating the union of these range of cells, we need to decide what we need to do with this union range of cells. Put dot (.) to see the IntelliSense list.

Code:

Sub Union_Example1()

  Union(Range("A1:A5"),Range("B3:B5")).

End Sub

VBA Union Example 1-4

Step 5 – We can see all the available properties and methods of these ranges.

For this example, I will change the Interior colour of union cells. For this I first I need to select the Interior property.

Code:

Sub Union_Example1()

  Union(Range("A1:A5"), Range("B3:B5")).Interior

End Sub

VBA Union Example 1-5

Step 6 – With interior property, we can do many things, but since we need to change the colour of the union cells, I will select Color property.

Code:

Sub Union_Example1()

  Union(Range("A1:A5"), Range("B3:B5")).Interior.Color

End Sub

Example 1-6

Step 7 – Now, we need to set the colour property. I will use a built-in colour index property as vbGreen.

Code:

Sub Union_Example1()

  Union(Range("A1:A5"), Range("B3:B5")).Interior.Color = vbGreen

End Sub

Example 1-7

Step 8 – Now if I run the code colours of the union cells will be changed to Green colour.

Example 1-8

Like this using Union method, we can create unison of two or more range of cells.

Example #2 – Use Variables to Store Range of Cells

All most all the coders use variables to store the reference of the range of cells. For example, look at the below code.

Code:

Sub Union_Example2()

  Dim Rng1 As Range
  Dim Rng2 As Range

  Set Rng1 = Range("A1:B5")
  Set Rng2 = Range("B3:D5")

  Union(Rng1, Rng2).Interior.Color = vbGreen

End Sub

First, I have declared two variables as Range.

Dim Rng1 As Range

Dim Rng2 As Range

Then I have set the reference for these two variables.

Set Rng1 = Range(“A1:B5”)

Set Rng2 = Range(“B3:D5”)

Now variable rng1 holds the reference of Range(“A1:B5”) and the second variable rng2 holds the reference of Range(“B3:D5”).

Then I have applied UNION function to change the interior colour of these range of cells.

This also works exactly the same as the previous one, but using variable makes the code very flexible to use.

Error with Union Function

As I told all the references should be mandatory for the UNION method. For example, look at the below code.

Code:

Sub Union_Example3()

  Dim Rng1 As Range
  Dim Rng2 As Range
  Dim Rng3 As Range

  Set Rng1 = Range("A1:B5")
  Set Rng2 = Range("B3:D5")

  Union(Rng1, Rng2, Rng3).Interior.Color = vbGreen

End Sub

This is similar to the previous, but here I have declared one more variable as Range.

Dim Rng3 As Range

But I have not set the reference to this variable. Rather I just supplied the variable to the UNION function.

Union(Rng1, Rng2, Rng3).Interior.Color = vbGreen

If I run this code, we will get the error like the below.

Error with Union

This is because whatever the variable we supply to the argument should hold some reference of the cells in the worksheet we are working on.

Recommended Articles

This has been a guide to VBA Union Method. Here we discuss how to join multiple ranges using excel VBA Union along with examples and download excel template. You may also have a look at other articles related to Excel VBA –

  • VBA TimeValue
  • Clear Contents in VBA
  • Excel VBA CDBL Function
  • Excel VBA ArrayList
  • VBA RegEx
title keywords f1_keywords ms.prod api_name ms.assetid ms.date ms.localizationpriority

Application.Union method (Excel)

vbaxl10.chm132112

vbaxl10.chm132112

excel

Excel.Application.Union

7c70a5be-2696-5fc2-bd69-6c6ff4d3291e

04/05/2019

medium

Application.Union method (Excel)

Returns the union of two or more ranges.

Syntax

expression.Union (Arg1, Arg2, Arg3, Arg4, Arg5, Arg6, Arg7, Arg8, Arg9, Arg10, Arg11, Arg12, Arg13, Arg14, Arg15, Arg16, Arg17, Arg18, Arg19, Arg20, Arg21, Arg22, Arg23, Arg24, Arg25, Arg26, Arg27, Arg28, Arg29, Arg30)

expression A variable that represents an Application object.

Parameters

Name Required/Optional Data type Description
Arg1 Required Range At least two Range objects must be specified.
Arg2 Required Range At least two Range objects must be specified.
Arg3Arg30 Optional Variant A range.

Return value

Range

Example

This example fills the union of two named ranges, Range1 and Range2, with the formula =RAND().

Worksheets("Sheet1").Activate 
Set bigRange = Application.Union(Range("Range1"), Range("Range2")) 
bigRange.Formula = "=RAND()"

This example compares the Worksheet.Range property, Application.Union method, and Application.Intersect method.

Range("A1:A10").Select                            'Selects cells A1 to A10.
Range(Range("A1"), Range("A10")).Select           'Selects cells A1 to A10.
Range("A1, A10").Select                          'Selects cells A1 and A10.
Union(Range("A1"), Range("A10")).Select           'Selects cells A1 and A10.
Range("A1:A5 A5:A10").Select                     'Selects cell A5.
Intersect(Range("A1:A5"), Range("A5:A10")).Select 'Selects cell A5.

[!includeSupport and feedback]

VBA Union

VBA Union

As the word itself suggests union means joining one or more things. In VBA Union means joining two or more ranges together. This function is similar to the range function in excel. This is the most common situation in our work when we need to combine one or more ranges with each other. Union function comes very handily in those situations.

VBA Union functions are used to combine one or more ranges as explained above. We can use this function to combine ranges that have some kind of common criteria. For example, if our data has value less than a specific value we can use this function to combine those ranges and highlight them.

Syntax of VBA Union in Excel

The syntax for Union function is as follows:

union Syntax

So for example, if we want to combine a range A1: A5 and B1: B5 we will use the following formula,

Union (Range (“A1:A5”), Range (“B1:B5”)

We can do much more with this function and we will see through various examples on how to use this function in VBA.

First, let us make sure that we have a developer’s tab enabled from the files tab in the options section so that we can start using VBA in excel.

How to Use VBA Union Function in Excel?

We will learn how to use a VBA Union function with few examples in excel.

You can download this VBA Union Excel Template here – VBA Union Excel Template

Example #1 – VBA Union

In the first example let us try to select two ranges together. Let us select A1:A5 and B1:B5 range together in this example.

Follow the below steps to use VBA Union function in Excel:

Step 1: Of course we need to open VB editor from visual basic which is in the developer’s tab.

VBA Union Example 1

Step 2: Now once we are in VB Editor go ahead and insert a new module from the insert section. The module we have inserted double click on it so that we can start writing code.

Module Union Example 1.1

Step 3: Once we are in the code window, name the macro as follows,

Code:

Sub sample()

End Sub

VBA Union Example1

Step 4: Since we will be working with sheet 1 we need to activate it first in order to use its properties.

Code:

Sub sample()

Worksheets("Sheet1").Activate

End Sub

WorkSheet 1 Active

Step 5: Now we will use union function to combine the two ranges we have discussed above with the following code.

Code:

Sub sample()

Worksheets("Sheet1").Activate
Application.Union(Range("A1:A5"), Range("B1:B5")).Select

End Sub

VBA Worksheet Active 1

Step 6: Once we execute the code above we can see in sheet 1 that those two ranges are in our selection. Press F5 or do it manually from run button to see the following result.

VBA Union Example 1

In the above example, we have only selected the two ranges but we can do much more which we will learn in the next examples.

Example #2 – VBA Union

Now in this example let us select two ranges as above together and change their interior color. We can change format or change values once we combine and select the ranges together.

Step 1: Go to Insert Menu and click on the module

Module union 2

Step 2: Declare a name for the subfunction for the second example,

Code:

Sub Sample1()

End Sub

Sub Sample

Step 3: Now let us activate sheet 2 first since we are going to use the properties of sheet 2 in this example.

Code:

Sub Sample1()

Worksheets("Sheet2").Activate

End Sub

WorkSheet 2 Active

Step 4: Combine two ranges A1:B5 and C1:D5 with range function and change the interior color to dark red by the following code.

Code:

Sub Sample1()

Worksheets("Sheet2").Activate
Application.Union(Range("A1:B5"), Range("C1:D5")).Interior.Color = 255

End Sub

WorkSheet Active 2

Step 5: Execute the above and see the result in sheet 2 as follows,

VBA Union 1

We have changed the color of the ranges after combining them as we can see that they are still in selection.

Example #3 – VBA Union

Now let use union function to display the address after combining ranges. We will combine range A1:C4 and E1:F4 and display the address in the Immediate window. An immediate window is just below our code window or we can press CTRL + G to bring it up.

Step 1:  Go to Insert Menu and click on the module,

Module

Step 2: Name the macro name for this third example.

Code:

Sub Sample2()

End Sub

VBA Union Example 3.1

Step 3: Declare two variables as a range in the next step as follows.

Code:

Sub Sample2()
Dim rng1 As Range
    Dim item As Range

End Sub

VBA Union Example 3.2

Step 4: Now set an rng1 variable as the union of the range A1: C4 and E1: F4 as follows,

Code:

Sub Sample2()
Dim rng1 As Range
    Dim item As Range
    Set rng1 = Union(Range("A1:C4"), Range("E1:F4"))
End Sub

VBA Union Example 3.3

Step 5: Now use for loop to bring the address of these cells from the combined ranges by the following code,

Code:

Sub Sample2()
Dim rng1 As Range
    Dim item As Range
    Set rng1 = Union(Range("A1:C4"), Range("E1:F4"))
    For Each item In rng1
        Debug.Print item.Address
    Next item
End Sub

VBA Union Example 3.4

Step 6: Once we run the above code we can see the result in the immediate window as follows,

VBA Union 3

Application of VBA Union

VBA union is used by the following syntax:

Expression.Union(range1, range2,…..)

Here we can use as many ranges as we require.

Things to Remember

There are few things which we need to remember about the union in VBA:

  • The union is used to combine two or more ranges together.
  • The ranges we give to the function must exist to avoid an error.
  • Instead of Application. Union we can simply use the union as we are working in excel itself.

Recommended Articles

This is a guide to VBA Union. Here we discuss how to use Excel VBA Union Function along with practical examples and downloadable excel template. You can also go through our other suggested articles –

  1. VBA Copy Paste
  2. VBA XML
  3. VBA Subscript out of Range
  4. VBA Login

Return to VBA Code Examples

In this Article

  • Union
  • Intersect
  • Use of Intersect

Excel VBA has two methods, belonging to Application object, to manipulate two or more ranges: Union and Intersect.

Union

Union method returns all the cells in two or more ranges passed as its argument.

The following command will select the range shown in the image below:

Union(Range("A1:B4"),Range("B3:C6")).Select

vba union selection

You can assign any value or formula to the range returned by the Union method:

Union(Range("A1:B4"), Range("B3:C6")) = 10

This will enter the value 10 in each cell in the Union.

You can wrap any function which summarizes a range around an Union method. Following example will return the sum of the values in the Ranges A1:B4 and B3:C6:

Result = Application.WorksheetFunction.Sum(union(Range("A1:B4"), Range("B3:C6")))

You might be surprised to get the value in Result as 160! Although there are only 14 cells in the Union (8 in each range with 2 being common) when you look at Selection, Union actually returns 16 cells hence the Result as 160.

Intersect

Intersect method returns only the common cells in two or more ranges passed as its argument.

The following command will select the range shown (Gray area) in the image below:

Intersect(Range("A1:B4"),Range("B3:C6")).Select

vba intersect selection

Use of Intersect

The most common usage of Intersect is in events associated with a Worksheet or Workbook. It is used to test whether the cell(s) changed belong to a a range of interest. Following example with check whether the cell(s) changed (identified by Target) and Range A1:A10  are common and take appropriate action if they are.

Intersect object returns nothing if there are no common cells so Intersect(Target, Range(“A1:A10”)) Is Nothing will be True if there are no common cells. Adding Not to the condition makes it True only if the result of the test Intersect(Target, Range(“A1:A10”)) Is Nothing is False, in other words Target and Range A1:A10 have some cells in common.

Private Sub Worksheet_Change(ByVal Target As Range)
	If Not Intersect(Target, Range("A1:A10")) Is Nothing Then
		' Take desired action
	End If
End Sub

Written by: Vinamra Chandra

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!
vba save as

Learn More!

Понравилась статья? Поделить с друзьями:
  • Vba excel автоматический запуск макроса
  • Vba excel vlookup пример
  • Vba excel type mismatch error 13 что
  • Vba excel автозапуск макроса
  • Vba excel vba tutorial