VBA Pridružite se - Koračni primjeri funkcije pridruživanja programa Excel VBA

Slično onome što u radnom listu imamo kao funkciju Concatenate i naredbu & koja se koristi za spajanje dva ili više niza zajedno, u VBA za to koristimo naredbu Join, u Join in VBA uzimamo izvor podataka u polju i slično spajanju koristimo graničnik da im se pridružimo.

Excel VBA funkcija PRIDRUŽIVANJA

Kao što i samo ime sugerira, funkcija VBA JOIN koristi se za spajanje niza podnizova s ​​navedenim graničnikom. Ako ne odredimo nijedan graničnik, tada je za zadani znak graničnika potreban 'razmak'. Radi na isti način kao što funkcija Concatenate radi u Excelu, osim što moramo samo jednom odrediti znak razgraničenja, dok u funkciji Concatenate moramo svaki put odrediti znak razgraničenja između svake dvije žice.

Sintaksa funkcije je

Kao što vidimo, funkcija uzima dva argumenta i vraća niz. Argumenti su:

  1. SourceArray : Moramo navesti ili dati referencu na niz podnizova koji se trebaju spojiti.
  2. Razdjelnik : Razgraničnik se koristi za odvajanje svakog od podnizova prilikom stvaranja rezultirajućeg niza. Budući da je ovo neobavezan argument, ako ga izostavimo, graničnik je postavljen kao razmak "".

VBA SPLIT funkcija potpuno je suprotna funkciji VBA JOIN funkcije.

Primjeri funkcije pridruživanja VBA

Ispod su primjeri funkcije pridruživanja u programu Excel VBA.

VBA pridruživanje - Primjer # 1

Pretpostavimo da se želimo pridružiti prvom (Ramesh), srednjem (Kumar) i prezimenu (Mishra).

Koraci bi bili:

  • Prvo, moramo otvoriti editor visual basic. To možemo učiniti klikom na naredbu 'Visual Basic' u grupi 'Code' na kartici 'Developer' excel ili možemo koristiti excel tipku prečaca Alt + F11 .
  • Umetnite modul desnim klikom na "list 1" i odabirom naredbe "Umetni" iz kontekstualnog izbornika, a zatim odaberite "Modul" za umetanje.
  • Stvorite potprogram pod nazivom 'JoiningName'.

Kodirati:

Sub JoiningName () Kraj Sub
  • Koristite funkciju JOIN na sljedeći način

Kodirati:

Sub JoiningName () Raspon ("D2"). Vrijednost = Pridruži se (Niz ("Ramesh", "Kumar", "Mishra")) Kraj Sub

Vidimo da smo koristili funkciju ARRAY za pružanje SourceArray-a funkciji JOIN i preskočili da odredimo znak za razdvajanje, tako da bi 'razmak' bio zadani znak. Obrađena vrijednost funkcije JOIN zapisat će se u ćeliju D2 kada izvršimo ovaj kod pomoću tipke F5 ili ručno.

VBA pridruživanje - Primjer # 2

Pretpostavimo da želimo stvoriti razne excel datoteke s nazivom predmeta koji sadrži prodaju samo za tu stavku.

  • Otvorite Visual Basic Editor pomoću tipke prečaca Alt + F11.
  • Desnom tipkom miša kliknite list 'Sheet1 ′ (Primjer 2)' da biste otvorili kontekstualni izbornik i kliknite na 'Insert' da biste umetnuli VBA 'modul' u VBA projekt.
  • Definirajte potprogram pod nazivom 'CreateItemSoldFiles'.

Kodirati:

Sub CreateItemSoldFiles () Kraj Sub
  • Moramo postaviti referencu na "Microsoft Scripting Runtime" knjižnicu objekata pomoću izbornika Alati -> Reference …, jer ćemo upotrijebiti neki kôd (objekte), koji neće raditi ako ne uključimo ovu knjižnicu objekata.
  • Sada ćemo proglasiti sve varijable.

Kodirati:

Zatamni FSO kao novi skript.FileSystemObject

Gornja FSO varijabla daje pristup VBA FileSystemObject. Nakon vezivanja možemo koristiti funkcije poput BuildPath, CopyFile, CreateTextFile itd.

  • Sljedeća izjava stvara objekt TextStream. Kroz objekt TextStream možemo čitati ili dodavati izvornu datoteku.

Kodirati:

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

Sada ćemo izvršiti kod, pritisnite F5, a zatim možemo vidjeti da je mapa nazvana 'Items_Sold' stvorena uz pomoć VBA koda na radnoj površini.

U mapi se nalazi 7 jedinstvenih datoteka stvorenih s imenima predmeta i možemo saznati detalje samo o toj određenoj stavci u datotekama.

Laptop.xls

Stvari koje biste trebali zapamtiti o funkciji VBA JOIN

  • SourceArray mora biti jednodimenzionalni niz. Ne možemo se odnositi na pojedinačnu ćeliju, jer će to stvoriti višestruke višedimenzionalne nizove.
  • Ako kao graničnik navedemo niz nulte duljine (""), sve će se stavke u nizu spajati bez graničnika.

Zanimljivi članci...