编辑 - 使用正则表达式进行泛型匹配,解决已澄清的问题。
使用正则表达式 (RegExp) 匹配模式“2 位,1 位非数字,3 位”。您将需要添加正则表达式参考。在 VBA 编辑器中,转到 Tools>References 并勾选
Microsoft VBScript Regular Expressions 5.5
然后将以下函数添加到您的模块中:
Function RegexMatch(Myrange As Range) As String
RegexMatch = ""
Dim strPattern As String: strPattern = "[0-9]{2}[a-zA-Z_\-]{1}[0-9]{3}"
Dim regEx As New RegExp
Dim strInput As String
strInput = Myrange.Value
With regEx
.Global = True
.MultiLine = True
.IgnoreCase = False
.Pattern = strPattern
End With
If regEx.Test(strInput) Then
RegexMatch = regEx.Execute(strInput)(0)
End If
End Function
然后像这样使用它:
Dim myCell As Range
Dim matchString As String
For Each myCell In Intersect(ActiveSheet.Columns("A"), ActiveSheet.UsedRange)
matchString = RegexMatch(myCell)
' Copy matched value to another column
myCell.Offset(0, 1).Value = matchString
Next myCell
结果:
有关 VBA RegExp 的更多信息,请参阅这个 SO 问题:
How to use Regular Expressions (Regex) in Microsoft Excel both in-cell and loops
原始 - 使用Instr 进行搜索字符串匹配。
你说得对,Instr 函数就是你想要的,如果字符串不在字符串中,则返回0,否则返回索引大于0。
Dim myString as String
myString = "Overlay 700 MHz - 06_469"
Dim myDigitString as String
' Use RIGHT to get the last 6 characters (your search string)
myDigitString = Right(myString, 6)
Dim myCell as Range
' Cycle through cells in column A, which are also in the sheet's used range
For each myCell in Intersect(ActiveSheet.Columns("A"), ActiveSheet.UsedRange)
If Instr(myCell.Value, myDigitString) > 0 Then
' Copy cell to another sheet
myCell.copy Desination:=ActiveWorkbook.Sheets("PasteToThisSheet").Range("A1")
' If you only want to get the first instance then...
Exit For
End If
Next myCell
要匹配模式“2 位,另一个字符,3 位”,您可以使用:
For each myCell in Intersect(ActiveSheet.Columns("A"), ActiveSheet.UsedRange)
' Check that first 2 digits and last 3 digits are in cell value
' Also check that they are separated by 1 character
If Instr(myCell.Value, Left(myDigitString,2)) > 0 And _
Instr(myCell.Value, Right(myDigitString,3)) > 0 And
Instr(myCell.Value, Right(myDigitString,3)) - Instr(myCell.Value, Left(myDigitString,2)) = 3 Then
' Copy cell to another sheet
myCell.copy Desination:=ActiveWorkbook.Sheets("PasteToThisSheet").Range("A1")
' If you only want to get the first instance then...
Exit For
End If
Next myCell