Union all excel vba

Содержание

  1. Метод Application.Union (Excel)
  2. Синтаксис
  3. Параметры
  4. Возвращаемое значение
  5. Пример
  6. Поддержка и обратная связь
  7. VBA Union
  8. Excel VBA Union
  9. Syntax
  10. How to use the VBA Union Method to Join Multiple Range?
  11. Example #1
  12. Example #2 – Use Variables to Store Range of Cells
  13. Error with Union Function
  14. Recommended Articles
  15. VBA Union — Как использовать функцию Excel VBA Union?
  16. VBA Union
  17. Синтаксис VBA Union в Excel
  18. Как использовать функцию объединения VBA в Excel?
  19. Пример № 1 — VBA Union
  20. Пример № 2 — VBA Union
  21. Пример № 3 — VBA Union
  22. Применение VBA Union
  23. То, что нужно запомнить
  24. Рекомендуемые статьи

Метод Application.Union (Excel)

Возвращает объединение двух или более диапазонов.

Синтаксис

выражение: переменная, представляющая объект Application.

Параметры

Имя Обязательный или необязательный Тип данных Описание
Arg1 Обязательный Range Необходимо указать по крайней мере два объекта Range .
Arg2 Обязательный Range Необходимо указать по крайней мере два объекта Range .
Arg3Arg30 Необязательный Variant Диапазон.

Возвращаемое значение

Пример

В этом примере объединение двух именованных диапазонов, Range1 и Range2, заполняется формулой =RAND().

В этом примере сравнивается свойство Worksheet.Range , метод Application.Union и метод Application.Intersect .

Поддержка и обратная связь

Есть вопросы или отзывы, касающиеся Office VBA или этой статьи? Руководство по другим способам получения поддержки и отправки отзывов см. в статье Поддержка Office VBA и обратная связь.

Источник

VBA Union

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.

Table of contents

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

Syntax

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

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 code Write The VBA Code VBA 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:

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

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?

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:

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:

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:

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:

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:

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:

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

Code:

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

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:

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:

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.

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 Union — Как использовать функцию Excel VBA Union?

VBA Union

Само по себе слово «союз» означает объединение одной или нескольких вещей. В VBA Union означает объединение двух или более диапазонов. Эта функция похожа на функцию диапазона в Excel. Это наиболее распространенная ситуация в нашей работе, когда нам нужно объединить один или несколько диапазонов друг с другом. Функция объединения в таких ситуациях очень удобна.

Функции VBA Union используются для объединения одного или нескольких диапазонов, как описано выше. Мы можем использовать эту функцию для объединения диапазонов, которые имеют какие-то общие критерии. Например, если наши данные имеют значение меньше определенного значения, мы можем использовать эту функцию, чтобы объединить эти диапазоны и выделить их.

Синтаксис VBA Union в Excel

Синтаксис для функции объединения выглядит следующим образом:

Так, например, если мы хотим объединить диапазон A1: A5 и B1: B5, мы будем использовать следующую формулу:

Союз (диапазон («A1: A5»), диапазон («B1: B5»)

С этой функцией мы можем сделать гораздо больше, и на разных примерах мы увидим, как использовать эту функцию в VBA.

Во-первых, давайте удостоверимся, что у нас включена вкладка разработчика на вкладке файлов в разделе параметров, чтобы мы могли начать использовать VBA в Excel.

Как использовать функцию объединения VBA в Excel?

Мы научимся использовать функцию VBA Union с несколькими примерами в Excel.

Вы можете скачать этот шаблон VBA Union Excel здесь — Шаблон VBA Union Excel

Пример № 1 — VBA Union

В первом примере попробуем выбрать два диапазона вместе. Давайте выберем диапазон A1: A5 и B1: B5 вместе в этом примере.

Чтобы использовать функцию VBA Union в Excel, выполните следующие действия:

Шаг 1: Конечно, нам нужно открыть редактор VB из Visual Basic, который находится на вкладке разработчика.

Шаг 2: Теперь, как только мы окажемся в VB Editor, добавьте новый модуль из раздела вставки. Модуль, который мы вставили, дважды щелкнул по нему, чтобы мы могли начать писать код.

Шаг 3: Как только мы окажемся в окне кода, назовите макрос следующим образом:

Код:

Шаг 4: Поскольку мы будем работать с листом 1, нам нужно сначала активировать его, чтобы использовать его свойства.

Код:

Шаг 5: Теперь мы будем использовать функцию объединения, чтобы объединить два диапазона, которые мы обсуждали выше, со следующим кодом.

Код:

Шаг 6: Как только мы выполним приведенный выше код, мы увидим на листе 1, что эти два диапазона находятся в нашем выборе. Нажмите F5 или сделайте это вручную с кнопки запуска, чтобы увидеть следующий результат.

В приведенном выше примере мы выбрали только два диапазона, но мы можем сделать гораздо больше, что мы узнаем в следующих примерах.

Пример № 2 — VBA Union

Теперь в этом примере давайте выберем два диапазона, как указано выше, и изменим их цвет интерьера. Мы можем изменить формат или изменить значения, как только мы объединяем и выбираем диапазоны вместе.

Шаг 1: Перейдите в меню «Вставка» и нажмите на модуль

Шаг 2. Объявите имя подфункции для второго примера.

Код:

Шаг 3: Теперь давайте сначала активируем лист 2, так как мы собираемся использовать свойства листа 2 в этом примере.

Код:

Шаг 4: Объедините два диапазона A1: B5 и C1: D5 с функцией диапазона и измените цвет салона на темно-красный с помощью следующего кода.

Код:

Шаг 5: Выполните вышеописанное и посмотрите результат на листе 2 следующим образом:

Мы изменили цвет диапазонов после их объединения, поскольку видим, что они все еще находятся в выделении.

Пример № 3 — VBA Union

Теперь давайте использовать функцию объединения для отображения адреса после объединения диапазонов. Мы скомбинируем диапазон A1: C4 и E1: F4 и отобразим адрес в окне Immediate. Непосредственное окно находится чуть ниже нашего окна кода, или мы можем нажать CTRL + G, чтобы вызвать его.

Шаг 1: Перейдите в меню «Вставка» и нажмите на модуль,

Шаг 2: Назовите имя макроса для этого третьего примера.

Код:

Шаг 3: Объявите две переменные в качестве диапазона на следующем шаге следующим образом.

Код:

Шаг 4: Теперь установите переменную rng1 как объединение диапазона A1: C4 и E1: F4 следующим образом:

Код:

Шаг 5: Теперь используйте цикл for, чтобы вывести адрес этих ячеек из объединенных диапазонов с помощью следующего кода:

Код:

Шаг 6: Как только мы запустим приведенный выше код, мы увидим результат в ближайшем окне следующим образом:

Применение VBA Union

VBA union использует следующий синтаксис:

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

Здесь мы можем использовать столько диапазонов, сколько нам нужно.

То, что нужно запомнить

Есть несколько вещей, которые мы должны помнить о союзе в VBA:

  • Объединение используется для объединения двух или более диапазонов вместе.
  • Диапазоны, которые мы даем функции, должны существовать, чтобы избежать ошибки.
  • Вместо приложения. Союз, мы можем просто использовать союз, так как мы работаем в самом Excel.

Рекомендуемые статьи

Это руководство к VBA Union. Здесь мы обсудим, как использовать функцию Excel VBA Union вместе с практическими примерами и загружаемым шаблоном Excel. Вы также можете просмотреть наши другие предлагаемые статьи —

  1. Функция копирования и вставки в VBA
  2. Функция подстроки Excel
  3. Индекс VBA вне диапазона
  4. Excel ISNUMBER Formula

Источник

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

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!

Определение блока ячеек, состоящего из объединения двух и более диапазонов, с помощью метода 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)

You can use ADO with Excel.

Dim cn As Object
Dim rs As Object
Dim strFile As String
Dim strCon As String
Dim strSQL As String
Dim s As String
Dim i As Integer, j As Integer

''This is not the best way to refer to the workbook
''you want, but it is very conveient for notes
''It is probably best to use the name of the workbook.

strFile = ActiveWorkbook.FullName

''Note that if HDR=No, F1,F2 etc are used for column names,
''if HDR=Yes, the names in the first row of the range
''can be used. 
''This is the Jet 4 connection string, you can get more
''here : http://www.connectionstrings.com/excel

strCon = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & strFile _
    & ";Extended Properties=""Excel 8.0;HDR=Yes;IMEX=1"";"

''Late binding, so no reference is needed

Set cn = CreateObject("ADODB.Connection")
Set rs = CreateObject("ADODB.Recordset")


cn.Open strCon

''A sample query
strSQL = "SELECT Distinct A, B C FROM ( " _
       & "SELECT A, B, C " _
       & "FROM [Sheet1$] " _
       & "UNION ALL " _
       & "SELECT A, B, C " _
       & "FROM [Sheet2$] ) As J "


''Open the recordset for more processing
''Cursor Type: 3, adOpenStatic
''Lock Type: 3, adLockOptimistic
''Not everything can be done with every cirsor type and 
''lock type. See http://www.w3schools.com/ado/met_rs_open.asp

rs.Open strSQL, cn, 3, 3

''Write out the data to an empty sheet (no headers)
Worksheets("Sheet3").Cells(2, 1).CopyFromRecordset rss

Like this post? Please share to your friends:
  • Unicode utf 8 word
  • Unicode utf 8 excel
  • Unicode in excel vba
  • Unicode font in word
  • Unicode characters in word