从句子中提取字母数字
我想有一个VBA从列G提取一个字母数字值是一个句子。
这句话通常是一个评论。 所以它包括字符和数字。
该值始终以AI0
开始并以0
结束。 这可以是11到13位数字。 有时这个数字在评论中被提及为AI038537500
,有时也被称为AI038593790000
。
我已经通过几乎所有的网站进行了研究,但没有发现任何这样的情况。 我知道公式, left
, right
, mid
但在我的情况下,它不适用。
任何领导都是可观的。
为什么不给以下的一个尝试?
Sub findMatches() Dim strLength As Integer Dim i As Long For i = 1 To Rows.Count Dim AllWords As Variant AllWords = Split(Cells(i, 7).Value, " ") For Each Item In AllWords strLength = Len(Item) If strLength > 0 And strLength <= 13 And Item Like "A10*?#" Then Cells(i, 8) = Item End If Next Next i End Sub
testing用例:
- 我是苹果,我的批号是:A10545440因此您需要知道
结果: A10545440
- 一些随机评论… A20548650
结果: 没有结果
- A101234567891是一个很棒的字母数字组合
结果: A101234567891
- 另一个随机评论… A10555
结果: A10555
注意:以上示例涵盖了从A10
开始的字母数字组合的情况是:
- 在一个句子的中间,或者
- 开始的一个句子,或者
- 在句子结尾
还要注意:现在它被设置为遍历所有的行…所以如果你想限制这个,把For
语句中的Rows.Count
更改为你设置的限制。
编辑:在上面的代码中,我明确要求它在列G中查找
你可以尝试这样的事情…
将以下用户自定义function放置在标准模块上,然后在工作表上使用
=GetAlphaNumericCode(A1)
UDF:
Function GetAlphaNumericCode(rng As Range) Dim Num As Long Dim RE As Object, Matches As Object Set RE = CreateObject("VBScript.RegExp") With RE .Global = False .Pattern = "AI\d{9,}0" End With If RE.Test(rng.Value) Then Set Matches = RE.Execute(rng.Value) GetAlphaNumericCode = Matches(0) Else GetAlphaNumericCode = "-" End If End Function
你可以试试这个吗? 我认为它应该做的工作,你也应该修改与列值的代码,我testing与C列的意见,而代码将写在D列。
Option Explicit Sub FindValue() Dim i As Long Dim lastrow As Long Dim lFirstChr As Long Dim lLastChr As Long Dim CodeName As String lastrow = activesheet.Range("c" & Rows.Count).End(xlUp).Row ' gets the last row with data in it For i = 1 To lastrow ' shuffles through all cell in data lFirstChr = InStr(1, Cells(i, 3), "A10") ' gets the coordinate of the first instance of "A10" If lFirstChr = 0 Then GoTo NextIteration lLastChr = InStr(lFirstChr, Cells(i, 3), " ") ' gets the coordinate of the first instansce of space after "A10" If lLastChr = 0 Then 'if there is no space after A10 then sets lastchr to the lenght of the string lLastChr = Len(Cells(i, 3)) End If CodeName = Mid(Cells(i, 3).Value, lFirstChr, lLastChr - lFirstChr) ' extracts the codename from the string value Range("d" & i).Value = CodeName Goto NextTteration NextIteration: Next i End Sub