我想让VBA从作为句子的列G中提取字母数字值。
这句话通常是评论。所以它包括字符和数字。
该值始终以AI0
开头,以0
结尾。这可以是11到13位数。有时,评论中会将该数字称为AI038537500
,有时也称为AI038593790000
。
我已经研究了几乎所有的网站,但没有发现这样的情况。我知道公式left
,right
,mid
,但就我而言,它并不适用。
任何领先都会很明显。
答案 0 :(得分:2)
您可以尝试这样的事情......
将以下用户定义函数放在标准模块上,然后在表格中使用它,如
=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
答案 1 :(得分:1)
为什么不试试下面这样的东西?
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
测试用例:
结果: A10545440
结果: 无结果
结果:A101234567891
结果: A10555
注意:上面的示例涵盖了以A10
开头的字母数字组合的情况:
另请注意:现在它设置为遍历所有行...因此,如果要限制它,请将Rows.Count
语句中的For
更改为您设置的限制。
修改强> 在上面的代码中,我明确要求它查看G列
答案 2 :(得分:0)
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