How to add string to string in excel

In column A, I have a list of random words, separated by «; «(semicolon & space),
and randomly having 1 to 3 words in each cell.

For example, A1 — A5 would contain the following:

apple
banana; carrot
durian; eggplant
fig
grape; honeydew; icecream

I am trying to surround each word with a specified string. For example, «I eat » before the word,
» everyday.», after the word, which should look like the following in column B.

I eat apple everday.
I eat banana everday.;I eat carrot everday.
I eat durian everday.; I eat eggplant everday.
I eat fig everday.
I eat grape everday.; I eat honeydew everday.; I eat icecream everday.

If each cell contains only one word, it would be a simple process of just concatenating:

=CONCATENATE("I eat ",A1," everyday.")

But then when the number of words are random, it starts to get confusing. Of course there is a solution by separating by the semicolons into different columns, add the new string, and add everything together, but I was going for doing it in a single cell.

Содержание

  1. VBA Concatenate Text Strings Together (& – Ampersand)
  2. Concatenate Strings
  3. Concatenate Cells
  4. Concatenate Variables
  5. Using the & Operator with Spaces
  6. Using the & Operator to Concatenate a Quotation Mark
  7. Putting Strings on a New line
  8. VBA Coding Made Easy
  9. VBA Code Examples Add-in
  10. Strings in VBA
  11. What is a String
  12. Concatenation
  13. String Manipulation
  14. Spaces — add or remove
  15. Replace
  16. Substring functions
  17. Left & Right
  18. Length or Position
  19. Search
  20. Summary
  21. Inserting into an Excel VBA string
  22. 3 Answers 3
  23. How can I concatenate strings in VBA?
  24. 3 Answers 3
  25. Linked
  26. Related
  27. Hot Network Questions
  28. Subscribe to RSS
  29. VBA Concatenate Strings with Ampersand Operator
  30. The VBA Tutorials Blog
  31. Introduction — VBA Concatenate Strings
  32. Example — VBA Concatenate Strings
  33. Tutorial — VBA Concatenate Strings
  34. How to concatenate strings with VBA
  35. How to concatenate quotation marks with VBA
  36. Common VBA Concatenate Errors
  37. Application Ideas

VBA Concatenate Text Strings Together (& – Ampersand)

In this Article

We have already gone over an introduction to string functions in our VBA Strings and Substrings Functions tutorial. We are now going to look at how to concatenate text strings.

Concatenate Strings

You can use the & operator in VBA to join text strings.

Concatenate Cells

You can also concatenate cells together. Below, we have the text strings in A1 and B1:

The following code shows you how to join text strings from cell A1 and B1 using the & operator, in cell C1:

Concatenate Variables

This is the full procedure to concatenate two cells together using string variables.

Using the & Operator with Spaces

When you want to include spaces you use & in conjunction with ” “. The following code shows you how you would include spaces:

Using the & Operator to Concatenate a Quotation Mark

Let’s say your text string contains a quotation mark, the following code shows you how to include a quotation mark within a text string:

Putting Strings on a New line

Let’s say you have five text strings, you can put each text string on a new line or paragraph, using either the vbNewLine, vbCrLf, vbCr or Chr Function. The following code shows you how to put each text string on a new line:

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 Code Examples Add-in

Easily access all of the code examples found on our site.

Simply navigate to the menu, click, and the code will be inserted directly into your module. .xlam add-in.

Источник

Strings in VBA

For a selection of other String function available in other languages but adapted for VBA, visit the additional string functions page with , StartsWith and EndsWith, Contains, PadLeft and PadRight, IsNullOrEmpty and more.

What is a String

The variable type is used to hold strings of text. Strings are a sequence of characters: alphabetical, numbers, special characters in any combination.

It is good programming practice to declare a variable and its type before using it because it prevents mistakes (see Option Explicit):

To give the variable a value the value has to be surrounded with double quotes:

Note
The Visual Basic interpreter tries to understand (resolve) any assignment of a variable given its type. The following would also be automatically converted to the string type: str = 100

Concatenation

Concatenation means the joining of multiple strings into a single string. You can do this with the & (most commonly used) or + (alternative) symbol.

. returns value for str1: abc_1230/08/2022

Note that VBA is not particular about the variable types you want to append, it will automatically convert the provided type to string in the process.

String Manipulation

There are many VBA’s built-in string functions that alter a string. Some of them we’ll study here: Trim, LCase and UCase, Space, Replace and StrReverse

LCase(String): Returns the lower case of the specified string

Ucase(String): Returns the upper case of the specified string

When you have to compare two variable values it can be important to check if all values are in the same case for the cases that it is not important if a value is written with capital or not. Then you use Lcase or Ucase before the values.

Spaces — add or remove

Space(number) — fills a string with a specified number of spaces. Used in combination with/ concatenated with other variables via the ‘&’-symbol. Note that more often you will simply create a string containing the required number of spaces.

Other functions concerning spaces remove spaces. As variable-values with or without erroneous spaces differ it is important to check if there are any spaces in values.

LTrim(String) Returns a string after removing the spaces on the left side of the specified string.
RTrim(String) Returns a string after removing the spaces on the right side of the specified string.
Trim(String) Returns a string value after removing both leading and trailing blank spaces.

Replace

Syntax: Replace( string_to_search, string_to_replace, replace_with [start, [count, [compare]]] )

The arguments between the [] are optional. Start: This is the position in string_to_search to begin the search. If this parameter is omitted, the Replace function will begin the search at position 1.
Count: This is the number of occurrences to replace. If this parameter is omitted, the REPLACE function will replace all occurrences of string_to_replace with replace_with.
Compare: This can be one of the following 2 values:vbBinary, the Compare Binary comparison or vbTextCompare, Textual comparison.

StrReverse(«abc»). Reverses the specified string: cba

Substring functions

Substring functions return only a certain part of the original string. VBA has a neat collection of such procedures discussed below.

Left & Right

The functions Left and Right return the first or last number of characters:

Mid(string_to_search, start_position, number_of_characters)
For extracting a substring, starting at the start_position somewhere in the middle of a string. If you want to extract a substring from a string starting in the middle until the end of it you can omit the third argument.

Length or Position

The Len(String) returns the length, the number of characters, of the string, including the blank spaces.

A common use of Len is to check if the string is empty or not, and let that determine what to do:

Search

InStr( [start], string_to_search, substring, [compare] ) ‘Returns the first occurence of the specified substring. Search happens from left to right.

On the first place you can give the startposition of the search, if omitted the search starts at the beginning. On the second place comes the text to search, and on the 3th place what you want to find. VBA will then give you an Integer back in return. This number is 0 if the string is not found. If the string is found then you get the location of the start of the string you were search for.

InStrRev(string1,string2[,start,[compare]])

InStrRev(» «codevbatool», «o») result:10
Returns the first occurence of the specified substring. Search happens from Right to Left. You get the place of the first occurence from the right of the string, but counted from the left. it checks its position from the forward direction and gives its position as the result.

The practical use of InStrRev can be in finding the last index of a character inside a string.

Summary

Function Name Description
InStr Returns the first occurence of the specified substring. Search happens from left to right.
InstrRev Returns the first occurence of the specified substring. Search happens from Right to Left.
Lcase Returns the lower case of the specified string.
Ucase Returns the Upper case of the specified string.
Left Returns a specific number of characters from the left side of the string.
Right Returns a specific number of characters from the Right side of the string.
Mid Returns a specific number of characters from a string based on the specified parameters.
Ltrim Returns a string after removing the spaces on the left side of the specified string.
Rtrim Returns a string after removing the spaces on the right side of the specified string.
Trim Returns a string value after removing both leading and trailing blank spaces.
Len Returns the lenght of the given string.
Replace Returns a string after replacing a string with another string.
Space Fills a string with the specified number of spaces.
StrComp Returns an integer value after comparing the two specified strings.
String Returns a String with a specified character the specified number of times.
StrReverse Returns a String after reversing the sequence of the characters of the given string.

Below image shows the Code VBA add-in support for VBA String procedures.

Источник

Inserting into an Excel VBA string

In JAVA or C++, we can do something along the line of myString.insert(position, word) . Is there a way we can do the same in Excel VBA’s string? In my worksheet, I have a string looks like this: 01 / 01 / 995 , I wants to insert a 1 into the year, so make it 01 / 01 / 1995 .

Is there another easier / more elegant way to do it?

3 Answers 3

I dont think there is a cleaner way of doing it so you could just wrap it up in a function. Another way of doing it would be with replace , but it’s not any cleaner.

or just modify what you have

This a version of the accepted answer, with added tests and working the way I would expect it to work:

Here is my fifty cents for this question.

First of all, I need to give credit to WONG, Ming Fung from wmfexel where I found this trick.

Unlike the VBA Replace function who asks for the String to replace, the Replace Worksheet function only asks for the position in the Origin String and the number of characters to overwrite.

By «abusing» this overwrite parameter, setting it to 0 allows us to add a given string at a specific position in an Orignin string by replacing 0 characters of it.

Here it how it works :

As you can see, it’s really convenient and readable. For those who are picky and thinks the name Replace is just confusing, Wrap it in an Insert function and you’ll be all done ;).

Источник

How can I concatenate strings in VBA?

This question comes from a comment under Range.Formula= in VBA throws a strange error.

I wrote that program by trial-and-error so I naturally tried + to concatenate strings.

But is & more correct than + for concatenating strings?

3 Answers 3

& is always evaluated in a string context, while + may not concatenate if one of the operands is no string:

This is simply a subtle source of potential bugs and therefore should be avoided. & always means «string concatenation», even if its arguments are non-strings:

The main (very interesting) difference for me is that:
«string» & Null -> «string»
while
«string» + Null -> Null

But that’s probably more useful in database apps like Access.

There is the concatenate function. For example But the & operator always concatenates strings. + often will work, but if there is a number in one of the cells, it won’t work as expected.

Linked

Hot Network Questions

To subscribe to this RSS feed, copy and paste this URL into your RSS reader.

Site design / logo © 2023 Stack Exchange Inc; user contributions licensed under CC BY-SA . rev 2023.3.20.43331

By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.

Источник

VBA Concatenate Strings with Ampersand Operator

The VBA Tutorials Blog

Introduction — VBA Concatenate Strings

In VBA, you concatenate strings into a single string using the & , or ampersand, operator. “Concatenate” is just a fancy way of saying “combine” or “join.” This isn’t just a VBA thing. The word “concatenate” is used in almost all programming languages. When you concatenate strings, you are joining them together into one string.

How you concatenate strings varies by programming language, but in VBA you simply add an ampersand between your strings to combine them into one string.

Just like most other VBA tasks, there are many different ways to combine VBA strings, but the & operator is the best way. If you’re familiar with my VBA tutorials, you no doubt have seen me use “&” to concatenate strings. This article will be the first time I’ve actually explained what the ampersand operator is and why concatenation is so valuable to understand.

For more tips and tricks for handling strings, check out my Working with Strings series.

Example — VBA Concatenate Strings

Make powerful macros with our free VBA Developer Kit

It’s easy to copy and paste a macro like this, but it’s harder make one on your own. To help you make macros like this, we built a free VBA Developer Kit and wrote the Big Book of Excel VBA Macros full of hundreds of pre-built macros to help you master file I/O, arrays, strings and more — grab your free copy below.

Tutorial — VBA Concatenate Strings

How to concatenate strings with VBA

In this example, the strings str1 and str2 are concatenated (or combined) into one string, strCombined . There’s no practical limit to how many strings you can combine together using & s. I mean, there is probably a limit but it’s not a practical one. Chances are you’ll be limited by the maximum number of characters in a string before you’re limited by how many ampersands you can have.

Take a look at this example to see what I mean:

In this example, multiple &s are used to join the strings into the combined string «180629» .

You’re not limited to using ampersands to concatenate string variables, either. You can actually use them to combine literal strings or strings and numbers. Check out this example, which combines a string and a number:

When you run this macro, you’ll be greeted with msgbox containing your combined string:

How to concatenate quotation marks with VBA

Concatenating quotation marks in VBA can be tricky since your strings are often surrounded by quotation marks. To combine strings that include quotation marks, you need to surround one or two quotation marks with a pair of quotation marks.

I know, it’s really confusing! Instead of trying to make sense of it with words, let’s look at an example.

The phrase mooo is now surrounded by quotation marks.

Okay, so it’s three consecutive quotation marks to display a quotation mark around typed strings. But what if you want a stand alone quotation mark around a variable? In that case, it’s four consecutive quotation marks to concatenate a quotation mark around a variable.

Makes perfect sense, right? I’m kidding. I know it’s tough, but it’s just one of those little things you have to memorize if you want to show quotation marks in your concatenated strings.

Common VBA Concatenate Errors

Notice in all my examples there’s a space between the variable and the & operator. This is extremely important because the ampersand has more than one meaning in VBA.

When a variable is immediately followed by an ampersand (with no space), it tells VBA you are trying to declare the variable as a Long data type. This is a very old feature of VBA that still exists for backward compatibility.

Let’s go up to my first example and try to remove the space between str1 and & . Your line of code will turn red and you’ll get an error, like this:

This is by far the biggest mistake I see when people are trying to concatenate strings. You must have a space before and after your ampersand to concatenate strings!

Another mistake I see people make is trying to combine strings with the + symbol. While it technically works when you have all strings, it won’t work the way you want it to when you trying combining strings and numbers. Case in point:

Notice how val2 isn’t a string because it’s not surrounded by quotes. When you try to combine the values using the plus symbol instead of the ampersand, VBA immediately interprets both values as numbers and adds them together. You’ll get a result of 30. If you used the ampersand to properly concatenate, you’d get the string 255.

The bottom line is you should ALWAYS use the & operator to concatenate VBA strings.

Application Ideas

One of the most practical uses for string concatenation is when you’re looping through all the rows in a range in Excel. You’ll often combine a column letter with an iterating row number to loop through different rows in a column. You’ve probably been concatenating without even realizing it!

Notice how I’m concatenating the string «A» with the integer i . This combines the variables in such a way that it checks all the values in cells A1, A2, …, A100. This is where the value of concatenation becomes evident. Concatenating strings and numbers to represent cells is the key component of automating Excel.

Almost every VBA article I write has some element of string concatenation. Take a look and see if you can spot them!

That’s all for this tutorial. When you’re ready to take your VBA to the next level, subscribe using the form below. After that, share this article on Facebook and Twitter, and you may inspire others to “do more with Excel.”

Ready to do more with VBA?
We put together a giant PDF with over 300 pre-built macros and we want you to have it for free. Enter your email address below and we’ll send you a copy along with our VBA Developer Kit, loaded with VBA tips, tricks and shortcuts.

Before we go, I want to let you know we designed a suite of VBA Cheat Sheets to make it easier for you to write better macros. We included over 200 tips and 140 macro examples so they have everything you need to know to become a better VBA programmer.

Источник

Turn REPLACE function into “INSERT” function

Sometimes, we want to add a text string, say “XX”, as a prefix or suffix to another text string.  This is quite easy with the function CONCATENATE, or even easier with the operator &.  However, what if we want to insertthe text string into a specific position in the middle of another text string ??

Excel Tips - Insert string

The function REPLACE comes to rescue.

Excel Tips - Insert string1

umm… REPLACE?

Excel Tips - Insert string2

According to its description,

it replaces (not insertspart of a text string with a different text string.

Shall we use a FUNCTION called “INSERT”?  Unfortunately there is no such “INSERT” function, as REPLACE could do it for us.  Let’s understand the syntax of REPLACE

REPLACE(old_text, start_num, num_chars, new_text)

  • Old_text    Required. Text in which you want to replace some characters.
  • Start_num    Required. The position of the character in old_text that you want to replace with new_text.
  • Num_chars    Required. The number of characters in old_text that you want REPLACE to replace with new_text.
  • New_text    Required. The text that will replace characters in old_text.

Source: Office Support

Well, having read the syntax and the explanation for each argument, we know that REPLACE can be used to convert “AAA-BBB-CCC” to “AAA-XXX-CCC” easily.  Let’s use our example to illustrate the function:

=REPLACE(A3,5,3,"XXX")
'where A3 resides the text string "AAA-BBB-CCC"

How it works?

  1. The formula looks into the text string “AAA-BBB-CCC’ in A3 (first argument: A3)
  2. Starting at the fifth position (second argument: 5)
  3. Replace three characters starting from there, i.e. “BBB” (third argument:3)
  4. with “XXX” (final argument: “XXX”)

As a result, “AAA-BBB-CCC” becomes “AAA-XXX-CCC”

Straight-forward.  Isn’t it?

But talking about to our task:

How to insert “XX” into a specific position of another text string?

No worry.  A simple trick turns REPLACE into “INSERT”.

And the trick is…… to put 0 as the third argument.

Let’s see how the following formula works:

=REPLACE(A3,5,0,"XX-")
'note the "-" at the end
'where A3 resides the text string "AAA-BBB-CCC"
  1. The formula looks into the text string “AAA-BBB-CCC’ in A3 (first argument: A3)
  2. Starting at the fifth position (second argument: 5)
  3. Replace zero character, i.e. nothing (third argument: 0)
  4. with “XX-” (final argument: “XX-“)

As a result, “AAA-BBB-CCC” becomes “AAA-XX-BBB-CCC”.

When we replace “nothing” with “something” at a specific position, we practically insert“something” at that position.  Make sense?  🙂

Learn Excel Dashboard Course

About MF

An Excel nerd who just transition into a role related to data analytics at current company……😊
Recently in love with Power Query and Power BI.😍
Keep learning new Excel and Power BI stuffs and be amazed by all the new discoveries.

This entry was posted in Formula and tagged CONCATENATE, REPLACE. Bookmark the permalink.

Excel for Microsoft 365 Excel for Microsoft 365 for Mac Excel for the web Excel 2021 Excel 2021 for Mac Excel 2019 Excel 2019 for Mac Excel 2016 Excel 2016 for Mac More…Less

The CONCAT function combines the text from multiple ranges and/or strings, but it doesn’t provide delimiter or IgnoreEmpty arguments. 

CONCAT replaces the CONCATENATE function. However, the CONCATENATE function will stay available for compatibility with earlier versions of Excel. 

Syntax

CONCAT(text1, [text2],…)

Argument

Description

text1

(required)

Text item to be joined. A string, or array of strings, such as a range of cells.

[text2, …]

(optional)

Additional text items to be joined. There can be a maximum of 253 text arguments for the text items. Each can be a string, or array of strings, such as a range of cells.

For example, =CONCAT(«The»,» «,»sun»,» «,»will»,» «,»come»,» «,»up»,» «,»tomorrow.») will return The sun will come up tomorrow.

Tip: To include delimiters (such as spacing or ampersands (&)) between the text you want to combine, and to remove empty arguments you don’t want to appear in the combined text result, you can use the TEXTJOIN function.

Remarks

  • If the resulting string exceeds 32767 characters (cell limit), CONCAT returns the #VALUE! error.

Examples

Copy the example data in each of the following tables, and paste it in cell A1 of a new Excel worksheet. For formulas to show results, select them, press F2, and then press Enter. If you need to, you can adjust the column widths to see all the data.

Example 1

=CONCAT(B:B, C:C)

A’s

B’s

a1

b1

a2

b2

a4

b4

a5

b5

a6

b6

a7

b7

Because this function allows full column and row references, it returns this result: A’sa1a2a4a5a6a7B’sb1b2b4b5b6b7

Example 2

=CONCAT(B2:C8)

A’s

B’s

a1

b1

a2

b2

a4

b4

a5

b5

a6

b6

a7

b7

Result: a1b1a2b2a4b4a5b5a6b6a7b7

Example 3

Data

First Name

Last name

brook trout

Andreas

Hauser

species

Fourth

Pine

32

Formula

Description

Result

=CONCAT(«Stream population for «, A2,» «, A3, » is «, A4, «/mile.»)

Creates a sentence by joining the data in column A with other text.

Stream population for brook trout species is 32/mile.

=CONCAT(B2,» «, C2)

Joins three things: the string in cell B2, a space character, and the value in cell C2.

Andreas Hauser

=CONCAT(C2, «, «, B2)

Joins three things: the string in cell C2, a string with a comma and a space character, and the value in cell B2.

Hauser, Andreas

=CONCAT(B3,» & «, C3)

Joins three things: the string in cell B3, a string consisting of a space with ampersand and another space, and the value in cell C3.

Fourth & Pine

=B3 & » & » & C3

Joins the same items as the previous example, but by using the ampersand (&) calculation operator instead of the CONCAT function.

Fourth & Pine

Need more help?

You can always ask an expert in the Excel Tech Community or get support in the Answers community.

See Also

CONCATENATE function

TEXTJOIN function

Overview of formulas in Excel

How to avoid broken formulas

Find and correct errors in formulas

Excel keyboard shortcuts and function keys

Text functions (reference)

Excel functions (alphabetical)

Excel functions (by category)

Need more help?

Use CONCATENATE, CONCAT, TEXTJOIN or the & operator in Excel to concatenate (join) two or more text strings.

1. The CONCATENATE function below concatenates the string in cell A1 and the string in cell B1.

CONCATENATE function in Excel

2. Use the & operator to produce the exact same result.

& Operator in Excel

3. The CONCATENATE function below concatenates the string in cell A1, the string » and » (enclose text in double quotation marks) and the string in cell B1.

CONCATENATE function with Three Arguments

4. Use the & operator to produce the exact same result.

Join Strings in Excel

5. The CONCATENATE function below concatenates the string in cell A1, a space and the string in cell B1.

Concatenation

6. Use the & operator to produce the exact same result.

Insert Space

The CONCAT function in Excel 2016 or later produces the exact same result as the CONCATENATE function. Simply replace CONCATENATE with CONCAT in the formulas shown above.

7. The CONCAT function can also join a range of strings. If you don’t need a delimiter (space, comma, dash, etc.) this can be useful.

CONCAT function in Excel

The TEXTJOIN function in Excel 2016 or later joins a range of strings using a delimiter (first argument).

8. First, take a look at all the extra spaces in column E below when you drag the CONCATENATE function in cell E2 down to cell E11.

CONCATENATE

9. The beauty of the TEXTJOIN function is that it can ignore empty cells (if the second argument is set to TRUE).

TEXTJOIN function in Excel

10. When using the CONCATENATE function, use the TEXT function to format numbers.

CONCATENATE and TEXT

Note: use 0 to display the nearest integer value. Use 0.0 for one decimal place. Use 0.00 for two decimal places, etc. Visit our page about the TEXT function for many more examples.

11. Use CHAR(10) to insert a line break.

Concatenation with Line Breaks

Note: don’t forget to enable text wrapping. On the Home tab, in the Alignment group, click Wrap Text.

12. Let’s take a look at one more cool example that uses the TEXTJOIN function. First, the IF function below finds all members of Team 1.

IF function

Explanation: the IF function checks each cell in the named range Teams. If equal to the value in cell E3, it returns the name from the named range Names, else it returns an empty string (two double quotes with nothing in between).

13. The IF function returns an array constant stored in Excel’s memory. Select the formula in the formula bar and press F9 to see this array constant.

Array Constant

14. Add the powerful TEXTJOIN function to concatenate these names. Use a comma and space as the delimiter (first argument) and set the second argument to TRUE to ignore the empty strings. Finish an array formula by pressing CTRL + SHIFT + ENTER.

Advanced TEXTJOIN formula

Note: Excel adds the curly braces {}. In Excel 365 or Excel 2021, finish by simply pressing Enter. You won’t see curly braces. Mia, James and Sophia are in Team 1. Double click the lower right corner of cell F3 to quickly copy this formula to the other cells.

Понравилась статья? Поделить с друзьями:
  • How many continent do we have in the word
  • How to add pictures in word
  • How many cell in excel
  • How to add pages in word
  • How to add page of page in word