vba 字符串首字母大写
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27669255/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Capitalizing first letter of strings
提问by bsapaka
I am trying to capitalize the first letter string sentin the array arr. The part of the code that does not work is the Rightfunction, which causes the code to return an error. What could be the fix?
我正在尝试sent将数组中的第一个字母字符串大写arr。代码中不起作用的部分是Right函数,它会导致代码返回错误。什么可以解决?
For Each sent In arr
sent = UCase(Left(sent, 1)) & Right(sent, Len(sent) - 1)
arr(i) = sent
i = i + 1
Next
回答by Sam
You can just use the StrConv()function for this. e.g. :
您可以StrConv()为此使用该功能。例如:
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), " ")
回答by Jason Faulkner
It would be easier to use the Midfunction for building everything after the letter capitalization. This function doesn't require that you specify the full length:
使用该Mid函数在字母大写后构建所有内容会更容易。此函数不要求您指定全长:
For i = LBound(arr) To UBound(arr)
sent = arr(i)
' Capitalize the first letter, then append everything else.
sent = UCase(Left(sent, 1)) & Mid(sent, 2)
arr(i) = sent
Next
Also, you can just iterate arrusing ias your enumerator. Mixing and matching index updates using a separate enumerator can lead to trouble.
此外,您可以arr使用i作为您的枚举器进行迭代。使用单独的枚举器混合和匹配索引更新可能会导致麻烦。
回答by Arthur
The difference between using strConvwith vbPropercaseand the the solution with UCase(left(xx,1)) & mid(xx,2)is that vbPropercasechanges 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.
使用strConvwithvbPropercase和解决方案 with之间的区别在于UCase(left(xx,1)) & mid(xx,2),vbPropercase将所有第一个字符更改为大写,将所有其他字符更改为小写。
这并不总是你想要的,有时你只想要第一个大写,其余的小写。
You then can use a slightly improved solution:
然后您可以使用稍微改进的解决方案:
UCase(Left(<string>,1)) & LCase(Mid(<string>,2))
回答by Ricardo
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()

