如果你可以帮助我,我需要找出一个字母表中的字符是否在一个单元格中连续重复3次或更多次,例如,如果一个单元格是“aronfff”或“aaaaaron”我希望它返回true,否则返回虚假,例如“aaron”。
Function InRowChars(cell As String) As Boolean
Dim repeats As Integer, char As String, i As Integer
repeats = 0
char = "abcdefghijklmnopqrstuvwxyz"
For i = 1 To Len(cell)
If cell.Value = " " Then
repeats = chars + 1
Else
chars = 0
End If
Next i
If chars = 3 Then
InRowChars = True
Else
InRowChars = False
End If
End Function
我不知道如何根据字母表来检查要检查的单元格的值。
答案 0 :(得分:4)
这可以通过正则表达式来实现。我已经创建了一个函数示例,它也接受了所需的最小字符数:
'Add a reference to Microsoft VBScript Regular Expressions 5.5
Function ContainsConsecutiveChars(ByRef CellRef As Range, Optional ConsecutiveCount As Long = 3) As Boolean
Dim chars() As String
chars = Split("a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z", ",")
With New RegExp
.Pattern = Join(chars, "{" & ConsecutiveCount & ",}|")
ContainsConsecutiveChars = .test(CellRef.Value2)
End With
End Function
答案 1 :(得分:2)
我发现你现在已经有了一个RegEx的答案。刚刚完成我的版本,所以我想发布它 @Thunderframe - 我喜欢可选位,因此我公然将它用于我的版本。
Public Function RepeatingChars(Target As Range, Optional ConsecutiveCount As Long = 3) As Variant
Dim RE As Object, REMatches As Object
Set RE = CreateObject("VBScript.RegExp")
With RE
.MultiLine = False
.Global = False
.IgnoreCase = True
.Pattern = "(.)\1{" & ConsecutiveCount - 1 & ",}"
End With
Set REMatches = RE.Execute(Target.Value)
If REMatches.Count = 0 Then
RepeatingChars = CVErr(xlErrNA)
Else
RepeatingChars = REMatches(0)
End If
End Function
该函数将返回任何字符的重复项,如果找不到匹配项,则返回#NA。
修改强>
在快速重新阅读您的问题后,您可以将整个If...End If
块替换为RepeatingChars = REMatches.Count <> 0
,以返回 TRUE / FALSE 。在这种情况下,请记住将函数的返回类型更改为Boolean
。
答案 2 :(得分:1)
这是我到目前为止所提出的:
Option Explicit
Function checkChars(inputCell As String, Optional repeat As Long = 3) As Boolean
Dim cnt As Long
Dim previous As String
Dim countResult As Long
For cnt = 1 To Len(inputCell)
If previous = Mid(inputCell, cnt, 1) Then
countResult = countResult + 1
Else
countResult = 1
End If
If countResult = (repeat) Then
checkChars = True
Exit Function
End If
previous = Mid(inputCell, cnt, 1)
Next cnt
End Function
Public Sub TestMe()
Debug.Print checkChars("lalaaa")
Debug.Print checkChars("lalaala", 2)
Debug.Print checkChars("lalaala", 1)
Debug.Print checkChars("lflalajajala", 2)
End Sub
我们的想法是,如果重复数不同于3,您也可以将重复数作为可选值传递。这是您从示例中获得的输出:
True
True
True
False
答案 3 :(得分:1)
这是另一个正则表达式解决方案,它返回TRUE或FALSE,具体取决于是否有三个或更多重复的字母字符:
Option Explicit
Function TripleChars(S As String) As Boolean
Dim RE As Object
Set RE = CreateObject("vbscript.regexp")
With RE
.Global = True
.Pattern = "([a-z])\1\1"
.ignorecase = True 'edit as desired
TripleChars = .test(S)
End With
End Function
以下是正则表达式的解释:
([a-z])\1\1
选项:不区分大小写; ^ $不匹配的换行
创建