VBA JOIN

VBA JOIN

Similar to what we have in a worksheet, as Concatenate function and the & command, one may join two or more two strings together. In VBA, we use the Join command to do so. In Join, we take the data source in an array, and similar to the concatenation, we use a delimiter to join them.

Excel VBA JOIN Function

As the name suggests, one may use the VBA JOIN function to combine an array of substrings with the specified delimiter. If we do not specify any delimiter, it takes ‘space’ as a default delimiter character. It does the same work as the Concatenate function in Excel, except we only have to specify the delimiter character once. In the Concatenate functionConcatenate FunctionThe CONCATENATE function in Excel helps the user concatenate or join two or more cell values which may be in the form of characters, strings or numbers.read more, we have to specify the delimiter character every time between every two strings.

The syntax of the function is

As we can see, the function takes two arguments and returns a string. Arguments are:

  1. SourceArray: We need to specify or reference an array of substrings joined.
  2. Delimiter: The delimiter is used to separate each substring when creating the resultant string. As this is an optional argument, if we omit it, the delimiter is set to be a space ‘ ‘.

The VBA SPLIT functionVBA SPLIT FunctionSplit function in VBA is used to split strings into multiple substrings based on a delimiter provided to the function and a comparison method. Unlike other string functions, split function can split a string into more than one substrings.read more is the opposite of the VBA JOIN function.

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

Examples of VBA Join Function

Below are examples of the Join function in Excel VBA.

VBA Join – Example #1

Suppose we want to join the first (Ramesh), middle (Kumar), and last name (Mishra).

Steps would be:

  • First, we need to open the Visual Basic Editor. We can do the same by clicking on the ‘Visual Basic’ command in the ‘Code’ group under the ‘Developer’ tab excel’Developer’ Tab ExcelEnabling the developer tab in excel can help the user perform various functions for VBA, Macros and Add-ins like importing and exporting XML, designing forms, etc. This tab is disabled by default on excel; thus, the user needs to enable it first from the options menu.read more or using use the excel shortcut keyThe Excel Shortcut KeyAn Excel shortcut is a technique of performing a manual task in a quicker way.read more Alt+F11.
  • Insert the module by right-clicking on ‘sheet 1’ and choosing the ‘Insert’ command from the contextual menu, and then choose ‘Module’ to insert.
  • Create a subroutine named ‘JoiningName’.

Code:

Sub JoiningName() End Sub

  • Use the JOIN function as follows.

Code:

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

We can see that we have used the ARRAY function to provide SourceArray to the JOIN function and skipped to specify the delimiter character, so ‘space’ would be the default character. The processed value of the JOIN function will be written in cell D2 when we execute this code using the F5 key or manually.

VBA Join – Example #2

Suppose we want to create various Excel files with the item name containing sales only for that item.

  • Open the Visual Basic Editor using the shortcut key Alt+F11.
  • Right-click on the ‘Sheet1′ (Example 2)’ sheet to open the contextual menu and click on ‘Insert’ to insert a VBA ‘Module’Insert A VBA ‘Module’Users have the ability to construct their own VBA Objects in VBA Class Modules. The objects created in this module can be used in any VBA project.read more in the VBA project.
  • Define a subroutine named ‘CreateItemSoldFiles’.

Code:

Sub CreateItemSoldFiles() End Sub

  • We need to set a reference to the ‘Microsoft Scripting Runtime’ object library using the 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 FileSystemObjectVBA FileSystemObjectVBA FileSystemObject (FSO) is similar to FileDialog in that it is used to access other files on the computer we are working on. We can also edit these files, which means we can read or write to them.read more. 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 the 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

  • We will define the following statement to count the total number of columns in the range.

Code:

cols = Range(“A1”).CurrentRegion.Columns.Count

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

  • We will write the following statements for assigning the variable ‘FolPath’ a path using the VBA ENVIRONVBA ENVIRONThe VBA ENVIRON function (stands for ENVIRONMENT) can be categorized as an Information Function which returns the values for an operating system environment variables. The variables contain information about profiles of all users and it returns a string value.read more 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 the B column one by one to ‘Items_Sold.’ We have used the ‘OFFSET function’ to get the reference of the cell in the 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 the ‘Items_Sold’ variable one by one in appending mode (it will append the new values at last).

Code:

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

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

  • We need to remember that the VBA JOIN function takes only a 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 several columns in the range.

As a delimiter, we have used the ‘vbTab’ keyword so that it would fill values in different cells.

  • As we have stored the processed value of the JOIN function into the ‘fs’ variable, we will write the fs’s values into new lines of VBALines Of VBAThe VBA new line function refers to creating the proper sentence and helps in aligning the sentence so that the correct message is conveyed to the users or readers. read more 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. 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

To execute the code, we will press F5. Then, we can see that it created a folder named ‘Items_Sold’ with the help of VBA code on the desktop.

In the folder, there are 7 unique files created with the names of the item. Therefore, we can find details about only that particular item in files.

Laptop.xls

Things to Remember About VBA JOIN Function

  • The SourceArray must be a one-dimensional array. Therefore, we cannot refer to an individual cell, as this will create multiple multi-dimensional arrays.
  • Suppose we specify a zero-length string (”) as a delimiter, all items in the array concatenated with no delimiters.

Recommended Articles

This article has been a guide to VBA Join. Here, we learn how to use the VBA Join function to combine an array of substrings with the specified delimiter, along with examples and downloadable templates. Below are some useful articles related to VBA: –

  • VBA Operators
  • VBA COUNTIF
  • VBA Now
  • VBA End
 

Related Posts