实际上,我的Excel电子表格中有多个字符串,其结构如下:
JOHN-MD-HOPKINS
REC-PW-RESIN我想使用正确的函数,但不包括字符串中包含在破折号(-)中的部分。
最终结果应该如下所示:
John-MD-Hopkins
Rec-PW-Resin是否有一个excel公式能够做到这一点?
发布于 2020-05-11 19:21:07
为此,您可能需要创建自己的VBA函数,检查数据中是否有两个连字符,如果是这样,则将第一个和最后一个单词转换为适当的大小写,而不触及中间的单词,否则只会将字符串转换为大小写。
将以下内容粘贴到Excel中的模块中:
Function fProperCase(strData As String) As String
Dim aData() As String
aData() = Split(strData, "-")
If UBound(aData) - LBound(aData) = 2 Then ' has two hyphens in the original data
fProperCase = StrConv(aData(LBound(aData)), vbProperCase) & "-" & aData(LBound(aData) + 1) & "-" & StrConv(aData(UBound(aData)), vbProperCase)
Else ' just do a normal string conversion to proper case
fProperCase = StrConv(strData, vbProperCase)
End If
End Function然后,在您的工作表中,您可以像使用任何内置公式一样使用它,所以如果“”在单元格A1中,那么您可以在另一个单元格中使用这个公式:
=fProperCase(A1)它将根据需要显示John-MD-Hopkins。
编辑代码
由于要求保留第二个单词,那么这个修改后的VBA函数(它“遍历”数组)应该可以工作:
Function fProperCase2(strData As String) As String
Dim aData() As String
Dim lngLoop1 As Long
aData() = Split(strData, "-")
For lngLoop1 = LBound(aData) To UBound(aData)
If (lngLoop1 = LBound(aData) + 1) And (lngLoop1 <> UBound(aData)) Then
aData(lngLoop1) = aData(lngLoop1)
Else
aData(lngLoop1) = StrConv(aData(lngLoop1), vbProperCase)
End If
Next lngLoop1
fProperCase2 = Join(aData, "-")
End Function它基本上是看正在处理的数组元素是否是第二个(lngLoop1=LBound(aData)+1),而不是最后一个(lngLoop1<>UBound(aData))。
致以敬意,
https://stackoverflow.com/questions/61737064
复制相似问题