Dynamic String Manipulation VBA Excel - vba

I have a string from a Sharepoint list that returns data like this:
"Doe, John;#44" or "Doe, Jane;#150".
I need to be able to remove the semicolon and any characters after that. Since they can be 4, 5 or even 6 characters I can't use the right function.

You can use InStr to locate the semicolon and the Left to extract the part to the left of it:
Sub test()
Dim s As String, i As Long
s = "Doe, John;#44"
i = InStr(1, s, ";")
s = Left(s, i - 1)
Debug.Print s
End Sub
This prints Doe, John

You can use the formula REPLACE(LEFT(A1,FIND(";",A1)-1),1,1,), assuming data is in cell A1.

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

VBA: using index and match with two columns as criterias (INCOMPATIBLE VARIABLE ERROR) [duplicate]

So in Excel, we know it's possible to test against multiple criteria via concatenation, like this:
MATCH(criteria1&criteria2, Range(), 0)
where criteria1 and criteria2 are 2 separate criteria.
I'm trying to automate this thing in Excel VBA, like this:
WorksheetFunction.Match(criteria1 + "&" + criteria2, Range(), 0)
My question is, how do I replicate the same concatenation of criteria with the ampersand, in VBA form? In the version above, Excel keeps telling me it can't use the Match function of the WorkSheetFunction class, which I'm attributing to the failed concatenation attempt above. Any suggestions or advice would be greatly appreciated.
Oh, and here's a link to a Microsoft Knowledge Base article about using multiple criteria in MATCH(): http://support.microsoft.com/kb/59482
EDIT: I realized I wasn't putting 2 ranges to correspond with my 2 criteria. The problem is I don't know how to concatenate 2 ranges, because mine are in the form:
Range(Cells(1,columnIndex),Cells(rowCount,columnIndex))
as opposed to A1:A200. Any ideas on how to convert, or to concat the ranges in their current form?
This works:
Sub dural()
crit1 = "find "
crit2 = "happiness"
N = Application.WorksheetFunction.Match(crit1 & crit2, Range("A1:A10"), 0)
MsgBox N
End Sub
with, say A3 containing:
find happiness
EDIT#1:
Consider the case of multiple criteria in several columns. For example:
and we want VBA to retrieve the name of a small, black, dog
without VBA in a worksheet cell we can use:
=INDEX(D1:D100,SUMPRODUCT(--(A1:A100="dog")*(B1:B100="small")*(C1:C100="black")*ROW(1:100)),1)
to get the name Oscar
we can use the same formula in VBA
Sub luxation()
Dim s As String, s2 As String
s = "INDEX(D1:D100,SUMPRODUCT(--(A1:A100=""dog"")*(B1:B100=""small"")*(C1:C100=""black"")*ROW(1:100)),1)"
s2 = Evaluate(s)
MsgBox s2
End Sub
Doesn't readily map to a VBA implementation, but you can cheat a bit using Evaluate:
Sub Tester()
Dim v1, v2, f
v1 = "y"
v2 = 11
Sheet1.Names.Add Name:="X", RefersTo:=v1
Sheet1.Names.Add Name:="Y", RefersTo:=v2
f = "MATCH(X&Y,$A$2:$A$5&$B$2:$B$5, 0)"
Debug.Print Sheet1.Evaluate(f)
End Sub
or skipping the names:
Sub Tester2()
Const F_TEMPL As String = "MATCH(""{V1}""&""{V2}"",$A$2:$A$5&$B$2:$B$5, 0)"
Dim v1, v2, f
f = Replace(F_TEMPL, "{V1}", "x")
f = Replace(f, "{V2}", 12)
Debug.Print Sheet1.Evaluate(f)
End Sub
You still need to send the MATCH argument body as a string. The '+' does not concatenate.
WorksheetFunction.Match(criteria1 & "&" & criteria2, Range(), 0)
Should concatenate the two values and execute the match.

How to Reference Special Characters Using Excel vba

I have several special characters in an excel spreadsheet. How do I reference them in Excel VBA?
The characters I need are not in the standard 255 ASCII codes.
I was thinking perhaps Chr(code) would work, but I'm not able to find the codes for the characters I need to test this.
User ChrW() instead of Chr() function to reference Unicode characters:
ChrW(23383) will produce 字.
Chr(23383) will throw an exception.
Use this script to see ChrW characters in F column
Sub caracter()
Dim caract As String
Dim r As Range
Dim i As Integer
caract = ChrW(633)
For i = 1 To 20000
caract = ChrW(i)
ActiveSheet.Cells(i, 6).Value = caract
Next i
End Sub

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.