我正在尝试构建一个UDF,它将查看一个单元格并删除以字母开头的所有单词的第一个字符" El" 除了第一个单词。
单元格A1中的值为:
El agua,El asma,El arca,Elhambre,El aguila,Elements
在将调用UDF函数的单元格B1中,我希望结果为:
El agua,l asma,l arca,lhambre,l aguila,lements
我的代码如下:
Function exceptFirst(MyString As String)
Dim X As Long
Dim Tempstr As String
Tempstr = ""
For X = 1 To Len(MyString)
If Mid(MyString, X, 2) = "El" Then
Tempstr = Tempstr
Else
Tempstr = Tempstr & Mid(MyString, X, 1)
End If
Next
exceptFirst = Tempstr
End Function
代码正在执行删除所有" E "的单词以开头" EL"但第一个单词中排除 第一次 出现次数。 非常感谢您的帮助,并提前致谢。
答案 0 :(得分:3)
另一个UDF,使用Split
& Join
Option Explicit
Option Compare Binary 'to ensure case sensitive
Function exceptFirst(S As String) As String
Dim V As Variant
Dim I As Long
Dim bFirst As Boolean
bFirst = False
V = Split(S, ", ")
For I = LBound(V) To UBound(V)
Select Case bFirst
Case False
If V(I) Like "El*" Then bFirst = True
Case True
If V(I) Like "El*" Then V(I) = Mid(V(I), 2)
End Select
Next I
exceptFirst = Join(V, ", ")
End Function
编辑我假设您希望 El
区分大小写,无论是替换还是检测哪个是第一个实例。如果不是这种情况,只需将Option Compare
语句从Binary
更改为Text
答案 1 :(得分:1)
建议Patrick
,您可以使用Split
函数来实现所需的输出...
Function exceptFirst(ByVal MyString As String) As String
Dim i As Long
Dim Tempstr As String
Dim str() As String
str() = Split(MyString, ", ")
Tempstr = str(0)
For i = 1 To UBound(str)
If LCase(Left(str(i), 2)) = "el" Then
Tempstr = Tempstr & ", " & Right(str(i), Len(str(i)) - 1)
Else
Tempstr = Tempstr & ", " & str(i)
End If
Next i
exceptFirst = Tempstr
End Function
答案 2 :(得分:0)
这是我设法建立的,使用您提供的样本:
Option Explicit
Function exceptFirst(MyString As String) As String
Dim varArr As Variant
Dim cnt As Long
Dim result As String
varArr = Split(MyString, ", ")
For cnt = LBound(varArr) To UBound(varArr)
If cnt > 0 Then
If UCase(Left(varArr(cnt), 2)) = "EL" Then
result = result & Right(varArr(cnt), Len(varArr(cnt)) - 1) & ", "
Else
result = result & varArr(cnt) & ", "
End If
Else
result = varArr(0) & ", "
End If
Next cnt
exceptFirst = Left(result, Len(result) - 2)
End Function
Public Sub TestMe()
Debug.Print exceptFirst("El agua, El asma, Elhambre, El aguila, cska, Elements")
End Sub
它滥用了Left()
和Right()
的用法,但代码几乎提供了所需的内容。棘手的部分是它被,
剥离并在循环上将其添加回来。在代码的最后,当它返回字符串时,它会删除最后一个逗号和空格:exceptFirst = Left(result, Len(result) - 2)
答案 3 :(得分:0)
regex
:
Sub RegexTest()
Dim strInput As String, strPat As String
Dim rX As New RegExp
strPat = "(?:\s)(e)(?=l)"
strInput = "El agua, Elhambre, El sol, elanore, bella"
Debug.Print "Input: " & strInput
Debug.Print "Expected output: El agua, lhambre, l sol, lanore, bella"
With rX
.Global = True
.MultiLine = True
.IgnoreCase = True
.Pattern = strPat
End With
Debug.Print "Output: " & rX.Replace(strInput, " ")
End Sub
哪个应该给你
Input: El agua, Elhambre, El sol, elanore, bella
Expected output: El agua, lhambre, l sol, lanore, bella
Output: El agua, lhambre, l sol, lanore, bella
模式可以改进 - 我不知道为什么它在e
之前捕获空间,当它在非捕获组中时...但在这种情况下,黑客是插入一个空格在replace
。