Intersect vba excel примеры

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

Описание

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

Если общие ячейки для всех заданных диапазонов не обнаружены, метод Application.Intersect возвращает значение Nothing.

Если в качестве аргументов метода Application.Intersect указаны диапазоны из разных листов, возвращается ошибка.

Синтаксис

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

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

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

Пример

Sub Primer()

Dim rngis As Range, arg1 As Range, arg2 As Range, arg3 As Range

    Set arg1 = Range(«A1:F10»)

    Set arg2 = Range(«C4:I18»)

    Set arg3 = Range(«D1:F22»)

    Set rngis = Application.Intersect(arg1, arg2, arg3)

        If rngis Is Nothing Then

            MsgBox «Указанные диапазоны не пересекаются»

        Else

            MsgBox «Адрес пересечения диапазонов: « & rngis.Address

        End If

End Sub

Строку

Set rngis = Application.Intersect(arg1, arg2, arg3)

можно записать без использования переменных так:

Set rngis = Application.Intersect(Range(«A1:F10»), Range(«C4:I18»), Range(«D1:F22»))

Есть и другой способ определения пересечения диапазонов. Он заключается в использовании свойства Range объекта Worksheet*:

Set rngis = Range(«A1:F10 C4:I18 D1:F22»)

‘или

Set rngis = Range(arg1.Address & » « & arg2.Address & » « & arg3.Address)

Но у этого способа есть существенных недостаток – свойство Range возвращает ошибку, если пересечение указанных диапазонов не существует. Поэтому преимущество остается за методом Application.Intersect, который, в этом случае, возвратит значение Nothing.

* Если код VBA Excel работает со свойствами активного листа, объект Worksheet можно не указывать. Например, строка MsgBox Name отобразит имя активного листа.

title keywords f1_keywords ms.prod api_name ms.assetid ms.date

Application.Intersect Method (Excel)

vbaxl10.chm183099

vbaxl10.chm183099

excel

Excel.Application.Intersect

856d052a-3207-ced2-941c-b466cb880a93

06/08/2017

Application.Intersect Method (Excel)

Returns a Range object that represents the rectangular intersection of two or more ranges. If one or more ranges from a different worksheet are specified, an error will be returned.

Syntax

expression . Intersect( 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 The intersecting ranges. At least two Range objects must be specified.
Arg2 Required Range The intersecting ranges. At least two Range objects must be specified.
Arg3 Optional Variant The intersecting ranges. At least two Range objects must be specified.
Arg4 Optional Variant The intersecting ranges. At least two Range objects must be specified.
Arg5 Optional Variant The intersecting ranges. At least two Range objects must be specified.
Arg6 Optional Variant The intersecting ranges. At least two Range objects must be specified.
Arg7 Optional Variant The intersecting ranges. At least two Range objects must be specified.
Arg8 Optional Variant The intersecting ranges. At least two Range objects must be specified.
Arg9 Optional Variant The intersecting ranges. At least two Range objects must be specified.
Arg10 Optional Variant The intersecting ranges. At least two Range objects must be specified.
Arg11 Optional Variant The intersecting ranges. At least two Range objects must be specified.
Arg12 Optional Variant The intersecting ranges. At least two Range objects must be specified.
Arg13 Optional Variant The intersecting ranges. At least two Range objects must be specified.
Arg14 Optional Variant The intersecting ranges. At least two Range objects must be specified.
Arg15 Optional Variant The intersecting ranges. At least two Range objects must be specified.
Arg16 Optional Variant The intersecting ranges. At least two Range objects must be specified.
Arg17 Optional Variant The intersecting ranges. At least two Range objects must be specified.
Arg18 Optional Variant The intersecting ranges. At least two Range objects must be specified.
Arg19 Optional Variant The intersecting ranges. At least two Range objects must be specified.
Arg20 Optional Variant The intersecting ranges. At least two Range objects must be specified.
Arg21 Optional Variant The intersecting ranges. At least two Range objects must be specified.
Arg22 Optional Variant The intersecting ranges. At least two Range objects must be specified.
Arg23 Optional Variant The intersecting ranges. At least two Range objects must be specified.
Arg24 Optional Variant The intersecting ranges. At least two Range objects must be specified.
Arg25 Optional Variant The intersecting ranges. At least two Range objects must be specified.
Arg26 Optional Variant The intersecting ranges. At least two Range objects must be specified.
Arg27 Optional Variant The intersecting ranges. At least two Range objects must be specified.
Arg28 Optional Variant The intersecting ranges. At least two Range objects must be specified.
Arg29 Optional Variant The intersecting ranges. At least two Range objects must be specified.
Arg30 Optional Variant The intersecting ranges. At least two Range objects must be specified.

Return Value

Range

Example

This example selects the intersection of two named ranges, rg1 and rg2, on Sheet1. If the ranges don’t intersect, the example displays a message.

Worksheets("Sheet1").Activate 
Set isect = Application.Intersect(Range("rg1"), Range("rg2")) 
If isect Is Nothing Then 
 MsgBox "Ranges do not intersect" 
Else 
 isect.Select 
End If

See also

Concepts

Application Object

Excel VBA Intersect

VBA Intersect is used to get a range object that is an intersection of two or more ranges. Therefore, one should supply a minimum of two ranges to find the intersecting range point. All the other arguments are optional based on the requirement.

Table of contents
  • Excel VBA Intersect
    • Examples
      • Example #1
      • Example #2
      • Example #3
      • Example #4
    • Things to Remember
    • Recommended Articles

Below is the syntax of the VBA INTERSECT formula.

Intersect Formula

  • Arg1 as Range: First intersecting range.
  • Arg2 as Range: Second intersecting range.

In the below examples, we will see some of the useful techniques.

VBA Intersect

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 Intersect (wallstreetmojo.com)

Examples

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

Example #1

For example, use the below data.

VBA Intersect Example 1

Step 1: Declare the variable as a Variant.

Code:

Sub Intersect_Example()

  Dim MyValue As Variant

End Sub

VBA Intersect Step 1

Step 2: Assign the value through the Intersect formula for this variable.

Code:

Sub Intersect_Example()

  Dim MyValue As Variant

  MyValue = Intersect(

End Sub

VBA Intersect Step 2

Step 3: Select the first range as B2 to B9.

Code:

Sub Intersect_Example()

  Dim MyValue As Variant

  MyValue = Intersect(Range("B2:B9"),

End Sub

VBA Intersect Step 3

Step 4: Select the second range from A5 to D5.

Code:

Sub Intersect_Example()

  Dim MyValue As Variant

  MyValue = Intersect(Range("B2:B9"),Range("A5:D5")

End Sub

VBA Intersect Step 4

Step 5: We are testing with only two ranges here. Close the formula and select the method as a VBA Cell AddressCells are cells of the worksheet, and in VBA, when we refer to cells as a range property, we refer to the same cells. In VBA concepts, cells are also the same, no different from normal excel cells.read more.

Code:

Sub Intersect_Example()

  Dim MyValue As Variant

  MyValue = Intersect(Range("B2:B9"), Range("A5:D5")).Address

End Sub

Step 5

Step 6: Show the value in the message box in VBAVBA MsgBox function is an output function which displays the generalized message provided by the developer. This statement has no arguments and the personalized messages in this function are written under the double quotes while for the values the variable reference is provided.read more.

Code:

Sub Intersect_Example()

  Dim MyValue As Variant

  MyValue = Intersect(Range("B2:B9"), Range("A5:D5")).Address

  MsgBox MyValue

End Sub

Step 6

We are done and will see what we get in the message box.

Step 7

We got the result as B5, i.e., the cell address of the intersection point of the supplied range.

Like this using the VBA INTERSECT method, we can do many more things.

Example #2

Select the Intersection Cell

To select the supplied range’s intersection cell, use the code below.

Code:

Sub Intersect_Example2()

  Intersect(Range("B2:B9"), Range("A5:D5")).Select

End Sub

It will select the intersection cell of the supplied range.

Example 2

Example #3

Clear Content of the Intersection Cell: To clear the content of the intersection cell of the supplied range, use the code below.

Code:

Sub Intersect_Example2()

  Intersect(Range("B2:B9"), Range("A5:D5")).ClearContents

End Sub

Example #4

Change the Cell Color Background and Font Color of Intersection Cell: Change the background color of the intersection cell and the font color of the intersection cell value using the code below.

Code:

Sub Intersect_Example2()

 Intersect(Range("B2:B9"), Range("A5:D5")).Cells.Interior.Color = rgbBlue
 Intersect(Range("B2:B9"), Range("A5:D5")).Cells.Font.Color = rgbAliceBlue

End Sub

Change the Value of the Intersection Cell: Using the Intersect function, we can also change the value of that cell into something else.

Example 2-1

In the above data, the intersection value of the range “B2:B9” and “A5:D5” is cell B5, marked with blue. Now by supplying this range to intersect function, we can change the value to something else.

The below code will change the value from 29398 to “New Value.”

Code:

Sub Intersect_Example3()

  Intersect(Range("B2:B9"), Range("A5:D5")).Value = "New Value"

End Sub

Run the code above. We will get the word “New Value” in place of 29398.

Example 3

Like this, by using the Intersect function, we can play around with the middle position value of the supplied range.

Things to Remember

  • In Excel, to get the intersect value of the range, we need to give space characters between two ranges.
  • We can use VBA codingVBA 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 to highlight, format, delete or change, and do many other things to the intersection value.
  • We will get the middle two values if the multiple rows and columnsA cell is the intersection of rows and columns. Rows and columns make the software that is called excel. The area of excel worksheet is divided into rows and columns and at any point in time, if we want to refer a particular location of this area, we need to refer a cell.read more supply the Intersect function.

Recommended Articles

This article has been a guide to VBA Intersect. Here, we learn how to highlight, format, delete or change, and do many other things to the intersection value using the Excel VBA Intersect method with examples and download templates. Below are some useful Excel articles related to VBA: –

  • VBA Comment Block
  • VBA ChDir
  • Subscript Out of Range in VBA
  • Global Variables in VBA

VBA Intersect

Excel VBA Intersect

VBA Intersect in mathematics or in geometry means when two or more lines or area crosses each other. The common point or area created after that is called Intersection point or area. In excel also we can highlight and measure the Intersect area.

Syntax of Intersect Function in Excel VBA

Intersect function has the following syntax in Excel VBA :

Syntax of VBA Intersect

As we can see, Arg1 and Arg2 are mentioned, Range. And rest of the arguments are in brackets. Which means that the first two arguments must be selected as Range. Or in other words, minimum 2 areas must be included for finding Intersect. Rest of the arguments can be selected as Range or it can include some other things or parameters as well as per need. This syntax can accommodate a maximum of 30 Arguments.

How to Use Excel VBA Intersect Function?

We will learn how to use a VBA Intersect function with few examples in Excel.

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

VBA Intersect – Example #1

In the first example, we will highlight and create Intersection area when we have some dataset. For this, we have sample data which has 3 columns filled with numbers as shown below.

VBA Intersect Example 1-1

Now we need to find the area of intersection of an above data table using VBA Intersect. For this, follow the below steps:

Step 1: Go to the VBA window and open a Module from the Insert menu option as shown below.

VBA Intersect Example 1-2

We will get a blank window of the module.

Step 2: Now write Subcategory of VBA Intersect or in any other name as per your choice.

Code:

Sub VBAIntersect1()

End Sub

VBA Intersect Example 1-3

Step 3: Now directly insert Intersect command as shown below.

Code:

Sub VBAIntersect1()

Intersect(

End Sub

VBA Intersect Example 1-4

As we already explained the detailed syntax of Intersect, we will add an area of intersection. We can choose N number of ranges but a minimum of two Ranges should be there.

Let’s consider below an area of intersection where the first area is from A1 to B8, the second area is B3 to C12 and the third area is A7 to C10. We can consider and choose any combination of a pattern of intersections.

VBA Intersect Example 1-4A

Now let’s see at what point (/s) these areas meet and intersect each other. The common area created by all the above areas will be our area of intersection.

Step 4: Now in VBA Module of Intersect, select the first area range as shown below.

Code:

Sub VBAIntersect1()

Intersect(Range("A1:B8")

End Sub

VBA Intersect Example 1-5

We have added the first range, but our syntax is still incomplete.

Step 5: Now further insert rest of two areas which we have discussed above separated by commas.

Code:

Sub VBAIntersect1()

Intersect(Range("A1:B8"), Range("B3:C12"), Range("A7:C10"))

End Sub

VBA Intersect Example 1-6

Step 6: Now give the condition as “True”.

Code:

Sub VBAIntersect1()

Intersect(Range("A1:B8"), Range("B3:C12"), Range("A7:C10")) = True

End Sub

VBA Intersect Example 1-7

This completes our code.

Step 7: Now compile the code and run by clicking on the Play button which is located below the menu bar as shown below.

VBA Intersect Example 1-8

We will get the common area or intersected area which has value TRUE as shown above. Although we got the intersect area, that TRUE has replaced the data which was there in the intersected area.

Step 8: Now to avoid losing this we can change the background of color, those common cells to any color of our choice. For this after the syntax of Intersect use Interior function along with Color as shown below.

Code:

Sub VBAIntersect1()

Intersect(Range("A1:B8"), Range("B3:C12"), Range("A7:C10")).Interior.Color =

End Sub

Interior function Example 1-9

Step 9: Now in VBA, we cannot use the name of the color which we want to use directly. For this, we need to add “vb” which is used to activate the colors available in VBA. Now use it and add any name of the color of your choice. We are selecting Green here as shown below.

Code:

Sub VBAIntersect1()

Intersect(Range("A1:B8"), Range("B3:C12"), Range("A7:C10")).Interior.Color = vbGreen

End Sub

Interior function green color Example 1-10

Step 10: Now again compile the written code in one go as the code is quite small and run it.

VBA Intersect Example 1-11

We will see the color of the intersected area is changed to Green and common area which is created by the intersection of different 3 areas in B7 to B8.

VBA Intersect – Example #2

There is another but a quite a different way to use VBA Intersect. This time we use intersect in a specific worksheet. In Sheet2 we have marked an area from B4 to E8 as shown below.

VBA Intersect Example 2-1

Follow the below steps:

Step 1: In VBA, go to Sheet2 of current Workbook as shown below.

VBA Intersect Example 2-1.1

Step 2: Now select the Worksheet from this first drop down option. This will allow the code to be used in this current sheet only.

Select Worksheet Example 2-2

Step 3: And from the second drop-down select the option Change as shown below. This is used to target the changes done in the selected range.

Change Option Example 2-3

Step 4: We will write our code in the first Subcategory only.

Code:

Private Sub Worksheet_Change(ByVal Target As Range)

End Sub

VBA Intersect Example 2-4

Step 5: We will use the If-Else loop for forming a condition for intersect function.

Code:

Private Sub Worksheet_Change(ByVal Target As Range)

If

End If

End Sub

If-Else loop Example 2-5

Step 6: First select the target range from B4 to E8 as shown below. This will target intersect of the area covered in B4 to E8 mainly.

Code:

Private Sub Worksheet_Change(ByVal Target As Range)

If Intersect(Target, Range("B4:E8"))

End If

End Sub

VBA Intersect Example 2-6

Step 7: And if there is nothing in the target area then we need to write a statement which will redirect the code ahead.

Code:

Private Sub Worksheet_Change(ByVal Target As Range)

If Intersect(Target, Range("B4:E8")) Is Nothing Then

End If

End Sub

VBA Intersect Example 2-7

Step 8: And if really the target is out of range, we can use a message box with a message of alert as shown below.

Code:

Private Sub Worksheet_Change(ByVal Target As Range)

If Intersect(Target, Range("B4:E8")) Is Nothing Then

  MsgBox "Out of Range"

End If

End Sub

VBA Intersect Example 2-8

Step 9: And In the Else statement where something in written inside the box then we should get a prompt message if the written content is inside the box as shown below.

Code:

Private Sub Worksheet_Change(ByVal Target As Range)

If Intersect(Target, Range("B4:E8")) Is Nothing Then

  MsgBox "Out of Range"

Else

  MsgBox "Within Range"

End If

End Sub

VBA Intersect Example 2-9

Step 10: Now compile each step of written code and close the worksheet of VBA. As we have written the code specific to the sheet then it will work in the same.

Step 11: Now write something inside the box.

Within Range Example 2-10

As we can see we wrote 2 in cell C5 inside the box we got the message or “Within Range”.

Step 12: Again write something out of the box. We wrote 1 in cell B10 and we got the message of “Out of Range” as shown below.

Out of Range Example 2-11

This is another way to using Intersect in Excel VBA.

Pros of Excel VBA Intersect

  • It is very easy to at least highlight the area which intersects by the process of example-1.
  • This is very useful where we need to filter or work on that kind of data which has intersection from a different area such as Dates, Owner, etc.

Things to Remember

  • Remember to save the file in Macro Enable Excel format, so that code will function in every use.
  • Writing code in Sheet instead of the module as shown in example-2, make the code applicable only for that sheet. That code will not work on any other sheet.
  • Using Target Range as shown in example-2 is useful in specifying the area to hit.

Recommended Articles

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

  1. VBA Loops
  2. VBA Web Scraping
  3. VBA Do Until Loop
  4. VBA CDEC

  • Excel VBA Intersect

Excel VBA Intersect

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

Синтаксис функции пересечения в Excel VBA

Функция пересечения имеет следующий синтаксис в Excel VBA:

Как мы видим, Arg1 и Arg2 упоминаются, Range. А остальные аргументы в скобках. Это означает, что первые два аргумента должны быть выбраны как Range. Или, другими словами, минимум 2 области должны быть включены для нахождения пересечения. Остальные аргументы могут быть выбраны как Range или могут включать в себя некоторые другие вещи или параметры, а также по мере необходимости. Этот синтаксис может содержать максимум 30 аргументов.

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

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

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

VBA Intersect — Пример № 1

В первом примере мы выделим и создадим область пересечения, когда у нас будет некоторый набор данных. Для этого у нас есть примеры данных, которые имеют 3 столбца, заполненных числами, как показано ниже.

Теперь нам нужно найти область пересечения вышеуказанной таблицы данных, используя VBA Intersect. Для этого выполните следующие шаги:

Шаг 1. Откройте окно VBA и откройте модуль из меню «Вставка», как показано ниже.

Мы получим пустое окно модуля.

Шаг 2: Теперь напишите Подкатегория VBA Intersect или под любым другим именем по вашему выбору.

Код:

 Sub VBAIntersect1 () End Sub 

Шаг 3: Теперь непосредственно вставьте команду Пересечь, как показано ниже.

Код:

 Sub VBAIntersect1 () Intersect (End Sub 

Как мы уже объясняли подробный синтаксис Intersect, мы добавим область пересечения. Мы можем выбрать N диапазонов, но должно быть минимум два диапазона.

Рассмотрим ниже область пересечения, где первая область от А1 до В8, вторая область от В3 до С12 и третья область от А7 до С10. Мы можем рассмотреть и выбрать любую комбинацию шаблона пересечений.

Теперь давайте посмотрим, в какой точке эти области встречаются и пересекаются друг с другом. Общая область, созданная всеми вышеупомянутыми областями, будет нашей областью пересечения.

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

Код:

 Sub VBAIntersect1 () Intersect (Range ("A1: B8") End Sub 

Мы добавили первый диапазон, но наш синтаксис все еще не завершен.

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

Код:

 Sub VBAIntersect1 () Intersect (диапазон («A1: B8»), диапазон («B3: C12»), диапазон («A7: C10»)) End Sub 

Шаг 6: Теперь задайте условие как «True».

Код:

 Sub VBAIntersect1 () Intersect (Range ("A1: B8"), Range ("B3: C12"), Range ("A7: C10")) = Истинный конец Sub 

Это завершает наш код.

Шаг 7: Теперь скомпилируйте код и запустите, нажав на кнопку Play, которая находится под строкой меню, как показано ниже.

Мы получим общую область или область пересечения, которая имеет значение ИСТИНА, как показано выше. Хотя мы получили область пересечения, эта ИСТИНА заменила данные, которые были в этой области.

Шаг 8: Теперь, чтобы не потерять это, мы можем изменить цвет фона, эти общие ячейки на любой цвет по нашему выбору. Для этого после синтаксиса Intersect используйте функцию Interior вместе с Color, как показано ниже.

Код:

 Sub VBAIntersect1 () Intersect (Range ("A1: B8"), Range ("B3: C12"), Range ("A7: C10")). Interior.Color = End Sub 

Шаг 9: Теперь в VBA мы не можем использовать название цвета, который мы хотим использовать напрямую. Для этого нам нужно добавить « vb », который используется для активации цветов, доступных в VBA. Теперь используйте его и добавьте любое название цвета по вашему выбору. Мы выбираем зеленый здесь, как показано ниже.

Код:

 Sub VBAIntersect1 () Intersect (Range ("A1: B8"), Range ("B3: C12"), Range ("A7: C10")). Interior.Color = vbGreen End Sub 

Шаг 10: Теперь снова скомпилируйте написанный код за один раз, так как код довольно маленький, и запустите его.

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

VBA Intersect — пример № 2

Существует другой, но совершенно другой способ использования VBA Intersect. На этот раз мы используем пересечение в конкретном листе. На Листе 2 мы отметили область от B4 до E8, как показано ниже.

Выполните следующие шаги:

Шаг 1: В VBA перейдите к Листу 2 текущей Рабочей книги, как показано ниже.

Шаг 2: Теперь выберите « Рабочий лист» в первом раскрывающемся списке. Это позволит использовать код только в этом текущем листе.

Шаг 3: И во втором раскрывающемся списке выберите параметр « Изменить», как показано ниже. Это используется для определения изменений, сделанных в выбранном диапазоне.

Шаг 4: Мы напишем наш код только в первой подкатегории.

Код:

 Private Sub Worksheet_Change (ByVal Target As Range) Конец Sub 

Шаг 5: Мы будем использовать цикл If-Else для формирования условия для функции пересечения.

Код:

 Private Sub Worksheet_Change (ByVal Target As Range), если End End, End End Sub 

Шаг 6: Сначала выберите целевой диапазон от B4 до E8, как показано ниже. Это будет нацелено на пересечение области, покрытой от B4 до E8 в основном.

Код:

 Private Sub Worksheet_Change (ByVal Target As Range) Если пересекается (Target, Range ("B4: E8")) End If End Sub 

Шаг 7: И если в целевой области ничего нет, нам нужно написать оператор, который будет перенаправлять код вперед.

Код:

 Private Sub Worksheet_Change (ByVal Target As Range) Если значение Intersect (Target, Range («B4: E8»))) равно нулю, то End End End End 

Шаг 8: И если действительно цель находится вне диапазона, мы можем использовать окно сообщения с сообщением о предупреждении, как показано ниже.

Код:

 Private Sub Worksheet_Change (ByVal Target As Range) Если значение Intersect (Target, Range ("B4: E8")) равно нулю, то MsgBox "Out of Range" End If End Sub 

Шаг 9: И в утверждении Else, где что-то написано внутри коробки, мы должны получить быстрое сообщение, если письменный контент находится внутри коробки, как показано ниже.

Код:

 Private Sub Worksheet_Change (ByVal Target As Range) Если значение Intersect (Target, Range ("B4: E8")) равно нулю, то MsgBox "Вне диапазона" Иначе MsgBox "В пределах диапазона" End If End Sub 

Шаг 10: Теперь скомпилируйте каждый шаг написанного кода и закройте рабочий лист VBA. Поскольку мы написали код, специфичный для листа, он будет работать так же.

Шаг 11: Теперь напишите что-нибудь внутри коробки.

Как мы видим, мы написали 2 в ячейке C5 внутри коробки, мы получили сообщение или « В пределах диапазона ».

Шаг 12: Снова напишите что-нибудь из коробки. Мы написали 1 в ячейке B10 и получили сообщение «Out of Range», как показано ниже.

Это еще один способ использования Intersect в Excel VBA.

Плюсы Excel VBA Intersect

  • Очень легко по крайней мере выделить область, которая пересекается в процессе примера 1.
  • Это очень полезно, когда нам нужно отфильтровать или обработать данные такого типа, которые пересекаются с другой областью, такой как даты, владелец и т. Д.

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

  • Не забудьте сохранить файл в формате Macro Enable Excel, чтобы код работал при каждом использовании.
  • Записав код на листе вместо модуля, как показано в примере 2, сделайте код применимым только для этого листа. Этот код не будет работать на любом другом листе.
  • Использование Target Range, как показано в примере 2, полезно при указании области для удара.

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

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

  1. Примеры по циклам VBA
  2. Excel КОЛОННА в номер
  3. VBA Do Loop
  4. Создать бюджет в Excel

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!

Понравилась статья? Поделить с друзьями:
  • Interruption of the word
  • Interrupting word or phrase
  • Interrogative sentences with question word
  • Interpretations of word meaning
  • Interpretation of word dream