How to trim or split variable name in VBA word - vba

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.

Related

How to get specific character before character in vbscript

I want to split a string in vbscript language.
The string contains : shipping costs 10%
I want to get the value before '%' but only the number.
I try with this but it doesn't work
spese = Split(spese,'%')(0)
Your code to retrieve everything before the % doesn't compile because you use conment signs as delimiter (') and not (")
After fixing that you also would have to cut out the value itself.
Regarding to the new conditions here is the solution in vb.net, assuming before the number there always is a blank:
Dim myString As String
myString = "shipping costs 10%"
Dim tmp As String
tmp = Left(myString, InStr(myString, "%") - 1)
Dim result As String
result = Right(tmp, Len(tmp) - InStrRev(tmp, " "))
The solution of #AndrewMorton (see comments of your question) is much more elegant. You should use it.

convert an integer variable to a string with leading zeros in VBA

For starters, there are LOTS of questions that have been asked with this topic. However all the ones I kept clicking on were in languages other than VBA and I did not understand the syntax of those languages.
When I did a google search I found this answer which seemed promising. AH FIDDLE STICKS! I just realized that answer for VB and probably explains why its not working in my VBA
Situation
I have a variable called DimScale that is an integer. I want to create a string called DimName that will start with "mm-" and be following by the integer from DimScale with leading 0s such that there are a minimum of characters after "mm-".
IF DimScale = 25
Then DimName = "mm-0025"
IF DimScale = 235
Then DimName = "mm-0235"
Note Dimscale >=1 and <= 9999
What I have tried
Dim Dimscale as Integer
Dim Dimension_Style_Name as String
String.Format("{0:0000}", DimScale)
Dimension_Style_Name = DimScale$
Dimension_Style_Name.Format("{0:0000}", DimScale)
I have read the gist too that Dimscale get converted to a string and then is sent through a loop of adding a leading zero until the length of the string equals the 4 characters in my case for the integer part.
I have also seen the case with IF statments where IF Dimscale <10 then "000"& If Dimscale <100 then "00"& etc.
Is there a way to do it like like the VB method in VBA?
maybe:
DimName = "mm-" & format(DimScale,"0000")
As per #MathieuGuindon valuable (as usual) contribution:
Format (fully-qualified VBA.Strings.Format) takes a Variant parameter, and returns a Variant - you can also use its little brother Format$, which takes a String and returns a String, eliminating implicit conversions along the way
I had a similar need to apply leading zeros ( 12 to 00012 ) to a specified range. But everything I'd found thus-far used an iterative cell-by-cell approach. I found an older but still valuable posting from SiddHarth Rout. His posting pertains to case conversion ( lower to upper case ) but I found it adapted nicely to applying leading zeros.
Here is link to SiddHarth's posting:
Convert an entire range to uppercase without looping through all the cells
Here is the adaptation for applying leading zeros to a specified range:
Sub rngLeadingZeros(rng As Range, nbrZeros As Integer)
' Add leading zeros to a specified range.
Dim strZeros As String
Dim x As Integer
'build string as required for text() function:
For x = 1 To nbrZeros
strZeros = strZeros & "0"
Next
'make sure the range is formatted as text:
rng.NumberFormat = "#"
'apply the format to the range:
rng = Evaluate("index(text(" & rng.Address & ", """ & strZeros & """),)")
End Sub
Sub testZ()
With ActiveSheet
rngLeadingZeros .Range("e3:e9"), 5
End With
End Sub

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.

using IndexOf in Mid function

Perhaps this is a simple solution for most, but I can't get this to work like it should according to syntax.
I have this line of text "Part Number123456Price$50.00"
I want to pull the part number out of it, so I use this function...
str = Mid(str, str.IndexOf("Part Number") + 12, str.IndexOf("Price"))
My results are str = "123456Price$50.0" every time. I know the part number can vary in length so I need a solid solution of pulling this out.
It can be confusing to mix the legacy VB string methods (such as Mid) with the .Net string methods (like IndexOf). The VB methods use 1 as the index of the first character while the .Net methods use 0.
The following code will extract the part number from a string
Dim str As String = "Part Number123456Price$50.00"
Dim iPart As Integer = str.IndexOf("Part Number") + 11
Dim iPrice As Integer = str.IndexOf("Price")
str = str.Substring(iPart, iPrice - iPart).Trim
The Mid() function of Visual Basic is documented as having three arguments: (1) a string, (2) the beginning location in the string, and (3) the number of characters to copy.
So if your string is "Part Number123456Price$50.00" and you want to pull the part number as a series of digits, the "123456" part of the string, using the Mid() function then you need to find the beginning of the part number digit string and to then know the number of digits.
If your string is in the variable str then you can find the offset by something like str.IndexOf("Number") + len("Number") which will provide the offset to after the string "Number".
Next you need to find the number of digits so you would do something like str.IndexOf("Price") to find where the text "Price" begins and then subtract from that offset the offset of where the digits begin.
The result of all of this is you need a bit of code something like the following. I have not tested this source as I am not a VB programmer so it may need a tweak and you might want to put some checks on data validity as well.
Dim TextNumber as String = "Number"
Dim TextPrice as String = "Price"
iOffset = str.IndexOf(TextNumber) + len(TextNumber)
str = Mid(str, iOffset, str.IndexOf(TextPrice) - iOffset)
Alternatively, if Price is always the format $00.00, this will also work.
Dim str as String = "Part Number123456Price$50.00"
str = str.Remove(str.IndexOf("Price"))

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.