Pulling names from a string in VBA - vba

For my code I need to make make strings from a main one that has the following format:
NAME_FAMILY_CITY_COUNTRY
I need each of those units to be separated to individual strings like:
NAME_
FAMILY_
CITY_
COUNTRY
As you can see the length of the variables in the original string might differ, I assume I need to use InStr with LEFT, MID, RIGHT functions, is that the direction I need to work forward?

Try this:
Dim x As String
x = "NAME_FAMILY_CITY_COUNTRY"
MsgBox Join(Split(x, "_"), vbCrLf) 'split by words separated by "_"
MsgBox Join(Split(Join(Split(x, "_"), "_|"), "|"), vbCrLf) 'add "_" at the end of each word...

Related

Combination of specific letters in many words

I have a database with a table called "sales person" which has a combination of names & surnames. On my report it must include the shortened name. Just the most left character of the Names and Surname combined. For example some has just one Name and a Surname, eg. "Pete Sampras". Combined it would show "PS" on my report. Some have more, like "Pete Steff Sampras". Combined it would be "PSS". For my own name is Johan vd Westhuizen. It must now look like "JVW". How would I go about it?
I am a beginner at this, and I'm not sure what to use. I have tried left(), but that's only for the first name
You can split the word in the spaces, and then use the Left() function to get the first character for each word.
In addition, convert it to upper case and trim to remove any spaces (I don't expect any but just in case).
See an example:
Public Function GetInitialsFromName(ByVal fullname As String) As String
'Array to hold the words
Dim arr As Variant
arr = Split(fullname, " ")
Dim initials As String, idx As Integer
'Loop each word, take the 1st letter and append it to the initials.
'Trim and convert to upper case.
For idx = LBound(arr) To UBound(arr)
initials = initials & StrConv(Left(Trim(arr(idx)), 1), vbUpperCase)
Next
GetInitialsFromName = initials
End Function
To call it:
Debug.Print GetInitialsFromName("Johan vd Westhuizen")
Debug.Print GetInitialsFromName("Pete Steff Sampras")
Debug.Print GetInitialsFromName("Pete Sampras")
'JVW
'PSS
'PS

How to parse this specific type of data in excel VBA?

I have a bunch of different sets of engineering measurements in the format:
77.170 (+/- 0.025)
And I need to split it into the first number, which is the nominal value, and the number in the parenthesis, the tolerance. Not sure exactly how to do this in excel VBA. I was thinking I would use the Split function with a space delimiter, giving me the first number, then the unnecessary characters, then the tolerance, but the tolerance will include a parenthesis. How could I get rid of just that parenthesis, and will what I just suggested even work? Thanks!
Consider:
Sub dural()
s = "77.170 (+/- 0.025)"
s2 = Replace(Replace(Replace(s, " ", ""), "+/-", ""), ")", "")
ary = Split(s2, "(")
MsgBox ary(0) & vbCrLf & ary(1)
End Sub
Use Text to Columns and a formula.
Go to Data--->Text to Columns. Choose delimited and choose Space as your delimiter. This should split the text string into something like:
ColA |ColB|ColC
77.170|(+/-|0.025)
Column C is a bit funky, so let's just grab everything but the last character.
In column D put this:
=LEFT(C1,LEN(C1)-1)
Finally, you should get:
ColA |ColB |ColC |ColD |
77.170|(+/- |0.025)|0.025|
I would use a combination of instr() and mid to get what you need. For example
measurments="77.170 (+/- 0.025)"
mid(measurements,1,instr(measurements," "))
trim(mid(measurements,instr(measurements,"-")+1,instr(measurements,")")-instr(measurements,"-")-1))
or, to combine,
measurments="77.170 (+/- 0.025)"
mid(measurements,1,instr(measurements," ")) & " " & trim(mid(measurements,instr(measurements,"-")+1,instr(measurements,")")-instr(measurements,"-")-1))
Try using a combination of InStr(), Left(), Right().
Get the index/position of the '(' using InStr and then extract the characters using Left and Right. If you want to get the final data as a double or a Long use CDbl() or CLng() respectively.
For getting text out of other text consider using Regular Expresions.
To use them in VBA you will need in Reference 'VBScript_RegExp_55' library.
The reason why you might want to do that is because following code returns whatever first two numbers show up in your text( it can be modified to be much smarter than that), regardless of other text around it.
Dim Regex As RegExp
Dim Matches As MatchCollection
Set Regex = New RegExp
Regex.Pattern = "\d*\.\d*"
Regex.Global = True
Set Matches = Regex.Execute("77.170 (+/- 0.025)")
MsgBox (Matches(0).Value & " " & Matches(1).Value)
Assuming s is your measurement string, here is the most direct way:
v = Split(Left(s, Len(s) - 1), " (+/- ")
That's it. Now v(0) holds the nominal value and v(1) holds the tolerance.

HOw to Split a string containg "" in VBA

I have a string like this adas:asd":"asd:asdas:dasd":"ad33q3sd:asd
I want to split it like
Dim splited() As String
splited = Split(input,"":"")
but its not working i tried adding \ but same
splited = Split(input,"\":\"")
Your Split should look like this:
splited = Split(input, """:""")
The first and last " define the string. The "" escapes each "
This "\":\"" is the C# notation
The other method works well, this is just a variation. vba has a function called chr(ascii_value), you supply the ascii value and chr returns the corresponding character. In this case a quote is ascii 34
splited = Split(input, chr(34) & "." & chr(34))
we've basically concatenated (&) our quotes with the period. using chr() for all your characters may be a bit silly and hard to read, but for quotes I think it's well used

How to trim or split variable name in VBA word

I have a variable like this:
var = "word1 (should be replaced by word1)"
I need to get word1 by itself and sometimes it may be a word(s) but it will always have (*) after it. Any way to delete text between the () signs, then remove the (), then remove any space(s) after the last word?
Not sure of any way to go about it.
The simplest would be:
var = Trim(Mid(var, 1, InStr(var, "(") - 1))
InStr returns the index of the first occurrance of "(". I subtract 1 to discount the position held by the "(".
Mid cuts the string from the first character at position 1, to the index returned by the InStr.
Then Trim to remove trailing spaces.
Like this?
Sub Sample()
Dim sVar As String
Dim MyAr() As String
sVar = "word1 (should be replaced by word1)"
MyAr = Split(sVar, "(")
Debug.Print MyAr(0)
End Sub
EDIT
The above code can be shortened further
Sub Sample()
Dim sVar As String
sVar = "word1 (should be replaced by word1)"
Debug.Print Split(sVar, "(")(0)
End Sub
I would use SPLIT function.
arrayVar2 = split(var, "(" )
You will now have an array with 2 elements.
Split the second element
arrayVar3 = split( arrayVar2[1], ")" )
Then join:
out = arrayVar2[0] & arrayVar3[1]
That will work as long as there is only ever a single set of brackets in the string.
The alternative way is to make use of the regular expression library but that is a longer answer. It wouldn't be as efficient but would be better if needing to handle more complex strings.
UPDATE: I went a bit further than the question perhaps called for. My solution ensures that the bracketed text is removed - any text AFTER the bracketed text is also retained.

How do I delete all characters after the first space in a cell?

I have a list of city names followed by the state in which they are located all in one column in Excel. How can I delete everything after the first space so that the city name is the only thing that's left in the cell?
example: A1 = "johnson TX"
should be just A1= "johnson"
I assume you want a VBA solution since you tagged your question excel-vba.
This works:
Sub KeepCity()
Dim strCityAndState As String
Dim strCityOnly As String
strCityAndState = Range("A1").Value
strCityOnly = Left(strCityAndState, InStr(strCityAndState, " ") - 1)
Range("A2").Value = strCityOnly
End Sub
If you don't want VBA and want a cell formula instead, then #JToland's answer works fine, though this one is more concise and doesn't keep the trailing space character:
=LEFT(A1, FIND(" ",A1)-1)
Well doing something like this
=Mid(A1, 1, Find(" ",A1))
in another column should grab all text before the " ". So you could build another column with just all the city names and then you could use that column for your purposes.
If you are looking for a VBA function, you can use Left and InStr as shown below.
Dim Temp As String: Temp = "Hello_World! This is my first answer here. :D"
Temp = Left(Temp, InStr(Temp, " ")-1)
In which case, Temp will be "Hello_World!"
Use of Split function
An elegant approach is to use the first token of the Split function:
Code Example extracting from cell A1 to A2
Option Explicit
Sub KeepCity()
Dim ws As Worksheet
Set ws = ThisWorkbook.Worksheets("MySheet") ' << Change to your sheet name
ws.[A2] = Split(ws.[A1], " ")(0)
End Sub
Alternative Syntax
Instead of cell abbreviations [A2] or [A1] you can also use:
ws.Range("A2").Value = Split(ws.Range("A1").Value, " ")(0)
Note
The resulting split 1-dimensional array is zero based, so you get the first part (or token) of the original string via index (0).
If you are looking for a second part, I recommend adding an additional delimiter value (" ") to the original string, e.g. s: MsgBox split(s & " "," ")(1). By that way you avoid error number 9 "Subscript out of range", if there is no delimiter in between at all, thus no second part at all.