How to add space in a string in excel vba? - excel

how can i add space in this example string?
Input value in cell A1 is ABCDEFGHIJK and will be paste in another cell B1 with a format of ABCDE FG HIJK.

One formula to insert a space:
=LEFT(A1,5)&" "&RIGHT(A1,LEN(A1)-5) to insert a space after the 5th position. (ABCDE FGHIJK)
One to insert 2 spaces as per example:
=LEFT(A1,5)&" "&MID(A1,6,2)&" "&RIGHT(A1,LEN(A1)-7)
Input ABCDEFGHIJK, result ABCDE FG HIJK
In short: Use =LEFT(), =RIGHT() and =MID() to get parts of your string and concatenate the parts and your spaces.
Edit:
In VBA:
Public Function StringWithSpaces(inpStr As String) As String
StringWithSpaces = Left(inpStr, 5) & " " & Mid(inpStr, 6, 2) & " " & Right(inpStr, Len(inpStr) - 7)
End Function

Related

Subtract string in one cell from another which are comma separated in excel [duplicate]

This question already has an answer here:
Subtracting a comma separated string from another one in Excel [closed]
(1 answer)
Closed 2 years ago.
How can I subtract a comma separated string from another one in Excel?
I want to subtract, A1 and A2 from A3 .
A1 - Wed,Thu
A2- Sun, Mon
A3- Mon,Tue,Wed,Thu,Fri,Sat,Sun
A4- Tue,Fri,Sat
I tried the following :-
=IF(ISERROR(SEARCH(A1,A3,1)),A3,RIGHT(A3,LEN(A3)-LEN(A1)))
But the output is not as what I wanted.
PS :- The A4 answer is the desired answer and not the answer I got after writing the above formula.
I'm assuming these values are delimited by comma-space. If not then adjust the formula accordingly (or use a double substitute to get rid of spaces before changing commas to tags).
In A4 try:
=TEXTJOIN(", ",1,FILTERXML(SUBSTITUTE("<t><s>"&A3&", "&A2&", "&A1&"</s></t>",", ","</s><s>"),"//s[not(following::*=. or preceding::*=.)]"))
Enter through CtrlShiftEnter
If FILTERXML does spark your interest, then have a look here for more possibilities.
Consider the following User Defined Function:
Option Explicit
Public Function RemoveItems(BigString As String, LittleString As String) As String
Dim Good As Boolean, L, B, arrB, arrL
Application.Volatile
arrB = Split(Replace(BigString, " ", ""), ",")
If InStr(LittleString, ",") = 0 Then
For Each B In arrB
If LittleString = B Then
Else
RemoveItems = RemoveItems & "," & B
End If
Next B
Else
arrL = Split(Replace(LittleString, " ", ""), ",")
For Each B In arrB
Good = True
For Each L In arrL
If L = B Then Good = False
Next L
If Good Then RemoveItems = RemoveItems & "," & B
Next B
End If
If RemoveItems <> "" Then RemoveItems = Mid(RemoveItems, 2)
End Function
It will remove items from the first comma-separated-string that appear in the second comma-separated-string. for example:
In your example, you would nest the calls:
=RemoveItems(RemoveItems(A3,A1),A2)
NOTES:
this version will accept a single item as well as a LettleString
this version removes spaces from the strings

Excel Finding Consecutive Phone Numbers

Is there a way in excel if I have a bunch of phone numbers in 1234567890 format, that I could find ranges and paste in the format of XXXXXXXXXX-XXXX?
I tried with some mid formulas but it's not working quite right.
=IF(A63=A62+1,A62 & "-" & A63,"NO ")
EDIT:
1234567890
1234567891
1234567892
1234567893
1234567897
1234567898
1234567899
5552221212
5552221213
Should look like:
1234567890-7893
1234567897-7899
5552221212-1213
EDIT 2:
If you throw in an odd ball between the mix say, 5555555555, I don't want to make 5555555555 link with any of those numbers.
For example, currently, I am looking at this further down on my spreadsheet: =IF(A209=A208+1,A208 & "-" & A209,A209). Basically, it posts the TN above it with the number after. What happens is going down the list above I'd get
1234567890 - 1234567891
1234567891 - 1234567892
Is there a way to make it show only 1234567890 - 1234567892?
If all the numbers are of the same format and you always want the "-" inserted before the last four numbers this will do the trick
In an excel formula:
=LEFT(A1;6) & "-" & RIGHT(A1;4)
In VBA
Dim text1 As String, text2 As String
For i = 1 To NumberOfRows
text1 = Cells(A,i)
text2 = Left(text1,6) + "-" + Right(text1,4)
Next i

Split Cell by Numbers Within Cell

I have some fields that need to be split up into different cells. They are in the following format:
Numbers on Mission 21 0 21
Numbers on Mission 5 1 6
The desired output would be 4 separate cells. The first would contain the words in the string "Numbers on Mission" and the subsequent cells would have each number, which is determined by a space. So for the first example the numbers to extract would be 21, 0, 21. Each would be in its own cell next to the string value. And for the second: 5, 1, 6.
I tried using a split function but wasn't sure how to target the numbers specifically, and to identify the numbers based on the spaces separating them.
Pertinent to your first case (Numbers on Mission), the simple solution could be as shown below:
Sub SplitCells()
Const RowHeader As String = "Numbers on Mission"
Dim ArrNum As Variant
ArrNum = Split(Replace(Range("A1"), RowHeader, ""), " ")
For i = 1 To UBound(ArrNum)
Cells(1, i + 2) = ArrNum(i)
Next
Cells(1, 2) = RowHeader
End Sub
The same logic is applicable to your second case. Hope this may help.
Unless I'm overlooking something, you may not need VBA at all. Have you tried the "Text to Columns" option? If you select the cell(s) with the information you would like to split up, and go to Data -> Text to Columns. There, you can choose "delimited" and choose a space as a delimiter, which will split your data into multiple cells, split by where the space is.
edit: Just realized that will also split up your string. In that case, when you are in 3rd part of the Text to Columns, choose a destaination cell that isn't the cell with your data. (I.E. if your data is in A1, choose B1 as destination, and it'll put the split info there. Then just combine the text columns with something like =B1&" "&C1&" "&D1)
I was able to properly split the values using the following:
If i.Value Like "*on Mission*" Then
x = Split(i, " ")
For y = 0 To UBound(x)
i.Offset(0, y + 1).Value = x(y)
Next y
End If

How to concatenate a list of words into a sentence with "and" before last item in Excel?

I want to join a list of words in Excel (not in VBA... with an Excel formula in the worksheet) to the following specifications:
Formula should ignore empty cells.
Formula should concatenate the words with "and" before final item if there is more than one item in the array of cells.
Formula should add "," between items if there are more than two items.
Examples:
A1=dog
A2=cat
A3=bird
A4=fish
Result would be: dog, cat, bird, and fish
A1=dog
A2=cat
A3=(empty cell)
A4=fish
Result would be: dog, cat, and fish
A1=dog
A2=(empty cell)
A3=bird
A4=(empty cell)
Result would be: dog and bird
A1=dog
A2=(empty cell)
A3=(empty cell)
A4=(empty cell)
Result would be: dog
Pretty please? I promise I've searched and searched for the answer.
Edit: Thank you, ExcelArchitect, I got it! This was the first time I'd ever used a custom function. You use it just like any other function in the worksheet! This is so great.
Not to push my luck, but how to do I get two cells to concatenate with my result if there is only one word in the result and two other cells if there is more than one word? Example: If the function you made for me returns just "dog", I'd want it to concatenate a cell with the text (B1) "My favorite thing to wear is a " and then "dog" and then another cell (B2) that says " costume." to make the sentence "My favorite thing to wear is a dog costume." But if it returns more than one animal, it would concatenate two other cells like this: Cell C1 "My favorite things to wear are " and "dog, cat, and bird" and Cell C2 " costumes." so that it would say "My favorite things to wear are dog, cat, and bird costumes."
If you're curious, my data really has nothing to do with animals or costumes. I am writing a program that will score a psychological test and then create an interpretive report from the test scores (I'm a psychologist).
-Mary Anne
Mary Anne:
This would be a great time to use VBA! But if you don't want to, there is a way to accomplish your goal without it.
You have to account for all of the possible outcomes here. With 4 different animals that means you have 15 outcomes:
Your equation just has to take into account all 15. It is VERY long and drawn out as a result. As such, if you have more than 4 animals that you'd like to turn into phrases, you should go the VBA route.
Here is my set up:
The formula in A7 is the following:
=IF(AND(A2<>"", A3="", A4="", A5=""), A2, IF(AND(A2="", A3<>"", A4="", A5=""), A3, IF(AND(A2="", A3="", A4<>"", A5=""), A4, IF(AND(A2="", A3="", A4="", A5<>""), A5, IF(AND(A2<>"", A3<>"", A4="", A5=""), A2&" and "&A3, IF(AND(A2<>"", A3="", A4<>"", A5=""), A2&" and "&A4, IF(AND(A2<>"", A3="", A4="", A5<>""), A2&" and "&A5, IF(AND(A2="", A3<>"", A4<>"", A5=""),A3&" and "&A4, IF(AND(A2="", A3<>"", A4="", A5<>""), A3&" and "&A5, IF(AND(A2="", A3="", A4<>"", A5<>""),A4&" and "&A5, IF(AND(A2<>"", A3<>"", A4<>"", A5=""), A2&", "&A3&", and "&A4, IF(AND(A2<>"", A3<>"", A4="", A5<>""), A2&", "&A3&", and "&A5, IF(AND(A2<>"", A3="", A4<>"", A5<>""), A2&", "&A4&", and "&A5, IF(AND(A2="", A3<>"", A4<>"", A5<>""), A3&", "&A4&", and "&A5, A2&", "&A3&", "&A4&", and "&A5))))))))))))))
Here it is via Excel:
Mary Anne - I'm such a nerd that I had to do this. Here is the VBA solution, and you can have as many names as you want! Paste this code into a new module in the workbook (go to Developer -> Visual Basic, then Insert -> New Module, and paste), then you can use it in your worksheet like a regular function. Just give it the range where the names are and you should be good to go! -Matt
Function CreatePhrase(NamesRng As Range) As String
'Creates a comma-separated phrase given a list of words or names
Dim Cell As Range
Dim l As Long
Dim cp As String
'Add commas between the values in the cells
For Each Cell In NamesRng
If Not IsEmpty(Cell) And Not Cell.Value = "" And Not Cell.Value = " " Then
cp = cp & Cell.Value & ", "
End If
Next Cell
'Remove trailing comma and space
If Right(cp, 2) = ", " Then cp = Left(cp, Len(cp) - 2)
'If there is only one value (no commas) then quit here
If InStr(1, cp, ",", vbTextCompare) = 0 Then
CreatePhrase = cp
Exit Function
End If
'Add "and" to the end of the phrase
For l = 1 To Len(cp)
If Mid(cp, Len(cp) - l + 1, 1) = "," Then
cp = Left(cp, Len(cp) - l + 2) & "and" & Right(cp, l - 1)
Exit For
End If
Next l
'If there are only two words or names (only one comma) then remove the comma
If InStr(InStr(1, cp, ",", vbTextCompare) + 1, cp, ",", vbTextCompare) = 0 Then
cp = Left(cp, InStr(1, cp, ",", vbTextCompare) - 1) & Right(cp, Len(cp) - InStr(1, cp, ",", vbTextCompare))
End If
CreatePhrase = cp
End Function
Hope that helps!
Matt, via ExcelArchitect.com
VBA is simpler. A formula is quite complicated, since Excel has no native functions allowing concatenation of a range. However, given that you have written that you would have up to eight animals, it is doable with the following formula which concatenates the contents of A1:A8 according to your rules. You can change those locations in the formula in the obvious locations.
I made one change: I may be wrong, but I believe English rules indicate that the comma preceding the last and should be omitted, so I did so. It could be added in if necessary. EDIT: Further investigation reveals a difference between US and UK rules: US rules are as you requested, UK rules omit the comma before the conjunction. I will modify the formulas and UDF to comply with US conventions.
In the formulas, the modification is to place a comma immediately prior to the and. The change in the UDF is likewise minor.
The formula was constructed from the following sequences:
So putting those formulas together, so as only to refer to A1:A8, we wind up with this monster:
=SUBSTITUTE(IFERROR(SUBSTITUTE(MID(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(CONCATENATE(",",A1,",",A2,",",A3,",",A4,",",A5,",",A6,",",A7,",",A8,","),",,",","),",,",","),",,",","),2,LEN(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(CONCATENATE(",",A1,",",A2,",",A3,",",A4,",",A5,",",A6,",",A7,",",A8,","),",,",","),",,",","),",,",","))-2),",",",and ",LEN(MID(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(CONCATENATE(",",A1,",",A2,",",A3,",",A4,",",A5,",",A6,",",A7,",",A8,","),",,",","),",,",","),",,",","),2,LEN(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(CONCATENATE(",",A1,",",A2,",",A3,",",A4,",",A5,",",A6,",",A7,",",A8,","),",,",","),",,",","),",,",","))-2))-LEN(SUBSTITUTE(MID(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(CONCATENATE(",",A1,",",A2,",",A3,",",A4,",",A5,",",A6,",",A7,",",A8,","),",,",","),",,",","),",,",","),2,LEN(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(CONCATENATE(",",A1,",",A2,",",A3,",",A4,",",A5,",",A6,",",A7,",",A8,","),",,",","),",,",","),",,",","))-2),",",""))),MID(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(CONCATENATE(",",A1,",",A2,",",A3,",",A4,",",A5,",",A6,",",A7,",",A8,","),",,",","),",,",","),",,",","),2,LEN(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(CONCATENATE(",",A1,",",A2,",",A3,",",A4,",",A5,",",A6,",",A7,",",A8,","),",,",","),",,",","),",,",","))-2)),",",", ")
Here is a VBA solution which will allow for any number of items; it concatenate according to the same rules as above.
Option Explicit
Function ConcatRangeWithAnd(RG As Range, Optional Delim As String = ", ")
Dim COL As Collection
Dim C As Range
Dim S As String
Dim I As Long
Set COL = New Collection
For Each C In RG
If Len(C.Text) > 0 Then COL.Add C.Text
Next C
Select Case COL.Count
Case 0
Exit Function
Case 1
ConcatRangeWithAnd = COL(1)
Case 2
ConcatRangeWithAnd = COL(1) & " and " & COL(2)
Case Else
For I = 1 To COL.Count - 1
S = S & COL(I) & ", "
Next I
ConcatRangeWithAnd = S & "and " & COL(COL.Count)
End Select
End Function
With the new TEXTJOIN function, this can be done very easily.
Step 1: Use TEXTJOIN function with the ", " delimiter, and set the ignore_empty to TRUE. This will give you comma separated, concatenated string, ignoring the blank values.
Step 2: Count the number of not blank entries in the list using COUNTA function. And subtract 1 from it. You might want to floor the value at 1 using the MAX function at this point.
Step 3: Use the SUBSTITUTE function to replace the last instance of the comma, which was calculated in Step 2, with a " and ".
Putting it all together:
=SUBSTITUTE(TEXTJOIN(", ",TRUE,A1:A14),", "," and ",MAX(1,COUNTA(A1:A14)-1))
Plug in any Range you want instead of A1:A14 in the above formula, and you will get a comma separated concatenate with an and before the last word.
Regarding duplicates:
Firstly, I really love Matt's solution and I've added this to my collection of custom functions.
What I do miss though is the possibility to remove duplicates from the phrase without removing them from the original range.
As you can't create a virtual range (a range that you can just play with in VBA independently from your source data), the solution would probably involve converting the range to an array, running some deduplication code and then creating the phrase from that.
My solution (albeit inelegant) is just to use the UNIQUE and FILTER functions to get a deduplicated list elsewhere on the spreadsheet (can be hidden if it bothers you) and to use Matt's function on that.
=UNIQUE(FILTER(yourRange,yourRange<>""))

String conversion with TEXT formula character limit?

I am attempting to format a single number stored as a text value.
For example, I would like to convert:
5145350002005000080
To:
5145-350002-00500-0080
The formula I am using is:
=text(A1,"0000-000000-00000-0000")
The output I am receiving is:
5145-350002-00500-0000
Why are the last 4 characters "0000" instead of "0080" as I would expect? Is there a character limit, or is my formula incorrect?
Quote from Large Number Arithmetic:
The limit in Excel is 15 significant digits in a number. Enter a 16
digit credit card number and 1234567890123456 will become
1234567890123450.
Actually, even 5145350002005001111 will result in 5145-350002-00500-0000.
Moreover, take a look at formula bar when your input cell is selected - for my Excel 2007 I see:
Hope that was helpful)
EDITED:
As a solution to solve the task - keep your numbers formatted as text and use the following formula:
=LEFT(A1,4)&"-"&MID(A1,5,6)&"-"&MID(A1,11,5)&"-"&RIGHT(A1,4)
Here is a custom function. Place it in a regular code module of the workbook and you can call it in the cell by =FormatLargeNumber("A1")
Public Function FormatLargeNumber(val As String)
'This function parses extremely large numbers per your example.
' Modify as needed.
FormatLargeNumber = Left(val, 4) & "-" _
& Mid(val, 5, 6) & "-" & _
Mid(val, 11, 5) & "-" & _
Right(val, 4)
End Function

Resources