'Capitalizing first letter of strings
I am trying to capitalize the first letter string sent in the array arr. The part of the code that does not work is the Right function, which causes the code to return an error. What could be the fix?
For Each sent In arr
sent = UCase(Left(sent, 1)) & Right(sent, Len(sent) - 1)
arr(i) = sent
i = i + 1
Next
Solution 1:[1]
You can just use the StrConv() function for this. e.g. :
For i = LBound(arr) To UBound(arr)
sent = arr(i)
arr(i) = StrConv(sent, vbProperCase)
Next
or without a loop:
arr = Split(StrConv(Join$(arr, " "), vbProperCase), " ")
Solution 2:[2]
The difference between using strConv with vbPropercase and the the solution with UCase(left(xx,1)) & mid(xx,2) is that vbPropercase changes all first characters to capitals and all others to lowercase.
That Is Not Always What You Want, sometimes you just want the first as an uppercase and the rest as a lowercase.
You then can use a slightly improved solution:
UCase(Left(<string>,1)) & LCase(Mid(<string>,2))
Solution 3:[3]
Try the following:
NewArr As List<string> NewArr = new List<string>()
For Each sent As String In arr
NewArr.Add(Application.WorksheetFunction.Proper(sent))
Next sent
arr = NewArr.ToArray()
Solution 4:[4]
In my case, the best solution was similar do Mid: =Replace(string, Left(string, 1), UCase(Left(string, 1)), , 1)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | greuze |
| Solution 3 | WonderWorker |
| Solution 4 | João Bortotti |
