Присъединяване към VBA - Поетапни примери за функция за присъединяване на VBA в Excel

Подобно на това, което имаме в работния лист като функция Concatenate и командата &, която се използва за свързване на два или повече от два низа заедно, във VBA използваме командата Join, за да го направим, в Join in VBA вземаме източник на данните в масив и подобно на конкатенацията, ние използваме разделител, за да се присъединим към тях.

Функция за присъединяване на Excel VBA

Както подсказва самото име, функцията VBA JOIN се използва за обединяване на масив от поднизове с посочения разделител. Ако не посочим какъвто и да е разделител, тогава това отнема „интервал“ като разделител по подразбиране. Той върши същата работа като функцията Concatenate в Excel, с изключение на това, че трябва да зададем разделител само веднъж, докато в функцията Concatenate трябва да указваме разделител всеки път между всеки два низа.

Синтаксисът на функцията е

Както виждаме, функцията взема два аргумента и връща низ. Аргументите са:

  1. SourceArray : Трябва да посочим или да дадем препратка към масив от поднизове, които трябва да бъдат обединени.
  2. Разделител : Разделителят се използва за разделяне на всеки от поднизовете при създаване на резултантния низ. Тъй като това е незадължителен аргумент, ако го пропуснем, разделителят е зададен като интервал ”“.

Функцията VBA SPLIT е точно противоположната функция на функцията VBA JOIN.

Примери за VBA функция за присъединяване

По-долу са примерите за функция за присъединяване в Excel VBA.

VBA присъединяване - Пример # 1

Да предположим, че искаме да се присъединим към първото (Ramesh), средното (Kumar) и фамилното име (Mishra).

Стъпките ще бъдат:

  • Първо, трябва да отворим редактора на visual basic. Ние можем да направим същото, като кликнете върху "Visual Basic" команда в групата "Кодекс" под "Разработчик" в раздела Excel или можем да използваме Excel клавиш Alt + F11 .
  • Поставете модула, като щракнете с десния бутон върху „лист 1“ и изберете командата „Вмъкване“ от контекстното меню и след това изберете „Модул“, който да вмъкнете.
  • Създайте подпрограма с име „JoiningName“.

Код:

Sub JoiningName () Край Sub
  • Използвайте функцията JOIN, както следва

Код:

Sub JoiningName () Range ("D2"). Value = Join (Array ("Ramesh", "Kumar", "Mishra")) End Sub

Можем да видим, че използвахме функцията ARRAY, за да предоставим SourceArray на функцията JOIN и пропуснахме да зададем разделителния знак, така че 'интервалът' ще бъде по подразбиране. Обработената стойност на функцията JOIN ще бъде записана в клетка D2, когато изпълним този код с помощта на клавиша F5 или ръчно.

Присъединяване към VBA - Пример # 2

Да предположим, че искаме да създадем различни Excel файлове с името на артикула, съдържащо продажби само за този елемент.

  • Отворете редактора на Visual Basic, като използвате клавишната комбинация Alt + F11.
  • Right click on ‘Sheet1′ (Example 2)’ sheet to open the contextual menu and click on ‘Insert’ to insert a VBA ‘Module’ in the VBA project.
  • Define a subroutine named ‘CreateItemSoldFiles’.

Code:

Sub CreateItemSoldFiles() End Sub
  • We need to set a reference to ‘Microsoft Scripting Runtime’ object library using Tools menu -> References… command, as we will use some code (objects), which will not work if we do not include this object library.
  • Now we will declare all the variables.

Code:

Dim FSO As New Scripting.FileSystemObject

The above FSO variable gives access to the VBA FileSystemObject. After binding, we can use functions like BuildPath, CopyFile, CreateTextFile, etc.

  • The next statement creates a TextStream object. Through the TextStream object, we can read from or append to the original file.

Code:

Dim FSO As New Scripting.FileSystemObject Dim ts As Scripting.TextStream
  • We will declare more variables. ‘r’ is for holding rows in the range, ‘fs’ is for storing final joined string, ‘cols’ for storing numbers of columns in the range, ‘FolPath’ for storing the path of the folder so that we can save the files in the folder and ‘Items_Sold’ for storing various item names to create a file with these names.

Code:

Dim r As Range Dim fs As String Dim cols As Integer Dim FolPath As String Dim Items_Sold As String
  • To count the total number of columns in range, we will define the following statement.

Code:

cols = Range("A1").CurrentRegion.Columns.Count

This statement will first select the current region for cell A1 and then will count the total number of columns in the current region.

  • We will write the following statements for assigning the variable ‘FolPath’ a path using VBA ENVIRON function and Concatenation Operator.

Code:

FolPath = Environ("UserProfile") & "DesktopItems_Sold" If Not FSO.FolderExists(FolPath) Then FSO.CreateFolder FolPath

The second statement will create the folder if the folder does not exist in the same location.

  • This code will assign the values of B column one by one to ‘Items_Sold’ We have used ‘OFFSET function’ to get the reference of cell in B column as the currently selected cell is in column A.

Code:

Items_Sold = r.Offset(0, 1).Value
  • The following bordered statement will open the files with names stored in ‘Items_Sold’ variable in one by one in appending mode (the new values will be appended at last).

Code:

Set ts = FSO.OpenTextFile(FolPath & " " & Items_Sold & ".xls", ForAppending, True)

We have used Concatenate operator with variables ‘FolPath’ and ‘Items_Sold’ and static values (“” and”.xls”) to create file names for excel files.

  • We need to keep in mind that VBA JOIN function takes an only one-dimensional array as SourceArray To convert the rows into a one-dimensional array, we need to use Application.Transpose method two times.

Code:

fs = Join(Application.Transpose(Application.Transpose(r.Resize(1, cols).Value)), vbTab)

We have used the Resize method of range object to resize the range to the width of a number of columns in the range.

As delimiter, we have used ‘vbTab’ keyword so that values would be filled in different cells.

  • As we have stored the processed value of JOIN function into ‘fs’ variable, we will write the fs’s values into new lines of VBA created excel files for every row in our original file from row number 2 to the last row (in our case it is 350th row).
  • Before ending the loop, we will close the file opened. The code would be as shown in the screenshot.

We have written the full code now.

Code:

Sub CreateItemSoldFiles() Dim FSO As New Scripting.FileSystemObject Dim ts As Scripting.TextStream Dim r As Range Dim fs As String Dim cols As Integer Dim FolPath As String Dim Items_Sold As String cols = Range("A1").CurrentRegion.Columns.Count FolPath = Environ("UserProfile") & "DesktopItems_Sold" If Not FSO.FolderExists(FolPath) Then FSO.CreateFolder FolPath For Each r In Range("A2", Range("A1").End(xlDown)) Items_Sold = r.Offset(0, 1).Value Set ts = FSO.OpenTextFile(FolPath & " " & Items_Sold & ".xls", ForAppending, True) fs = Join(Application.Transpose(Application.Transpose(r.Resize(1, cols).Value)), vbTab) ts.WriteLine fs ts.Close Next r End Sub

Сега, за да изпълним кода, ще натиснем F5, тогава можем да видим, че е създадена папка с име 'Items_Sold' с помощта на VBA код на работния плот.

В папката има 7 уникални файла, създадени с имената на елемента и ние можем да разберем подробности само за този конкретен елемент във файловете.

Laptop.xls

Неща, които трябва да запомните за функцията VBA JOIN

  • В SourceArray трябва да е едномерен масив. Не можем да се позовем на отделна клетка, тъй като това ще създаде множество многомерни масиви.
  • Ако посочим като разделител низ с нулева дължина (“”), всички елементи в масива се обединяват без разделители.

Интересни статии...