在带有随机字母和数字的文本字符串中找到数字的精确匹配

时间:2019-01-04 12:01:41

标签: excel vba excel-vba

我在B列的Sheet2中只有以B2开头的数字:81、102(在B3中),104(在B4中)等,而在A的Sheet1中以A2开头的数字是带有无数字的混合数字逻辑位置文本,例如:abc813bnm 12mn(在A2中),fgh 81lkj 45ol(在A3中),ert1042hji(在A4中),等等。我需要从col.A / Sheet1的col.B / Sheet2中搜索每个数字,并在col.Q的同一行上写入完全匹配的数据。他的第一个81的精确匹配在A3(fgh 81lkj 45ol)中,但不在A2(abc813bnm 12mn)中,它位于813弦中。在我的代码81中(不仅如此),它是“找到”的,在具有81的单元格和具有813的单元格中,我不希望这样:

子SearchLCL()

Application.Calculation = xlCalculationManual
Application.ScreenUpdating = False
Application.DisplayStatusBar = False
Application.EnableEvents = False

Dim LCL1 As String
Dim LCL2 As String
'Dim answer As String
Dim c As Range
Dim counter As Long
Dim totalLCL1 As Long
Dim totalLCL2 As Long

counter = 2

'Sheets("MailElibLCL").Select 'Sheet2
'Sheets("lucrari 2017").Select 'Sheet1

totalLCL2 = Worksheets("Sheet1").Range("A" & Rows.Count).End(xlUp).Row
totalLCL1 = Worksheets("Sheet2").Range("B" & Rows.Count).End(xlUp).Row

'totalLCL2 = N
'totalLCL1 = N3

For I = 2 To totalLCL2
'answer = Worksheets("hedis1").Range("h" & counter).Value
LCL2 = Worksheets("Sheet1").Range("A" & counter).Value
'LCL2 = "=MID(Worksheets.Sheet1.Range(""A"" & counter),SEARCH(LCL1,Worksheets.Sheet1.Range(""A"" & counter)),LEN(LCL1))"
k = "Q" & counter
For j = 2 To totalLCL1
    LCL1 = Worksheets("Sheet2").Range("B" & j).Value

     If InStr(1, LCL2, LCL1, vbTextCompare) > 0 Then
    Debug.Print LCL1

'If LCL1 = LCL2 Then
        'If answer = "Yes" Then
            For Each c In Worksheets("Sheet1").Range(k)

                'c.Value = Mid(LCL2, Search(LCL1, LCL2), Len(LCL1))
                'c.Formula = "=MID(LCL2,INSTR(LCL1,LCL2),LEN(LCL1))"
                'c.EntireRow.Interior.Color = 6 ' Change the number to match the desired color.
                c.Value = LCL1 '& vbLf & Date   'Now (si ora minute secunde)
                'c.Interior.Color = 5296210 ' Change the number to match the desired color.

            Next c
        'End If
    'End If
    End If
    Next j
counter = counter + 1
Next I

'Else    '致电ScrieMailElib    '如果结束

出错时转到0

Application.EnableEvents = True
Application.DisplayStatusBar = True
Application.ScreenUpdating = True
Application.Calculation = xlCalculationAutomatic

结束子

谢谢。

2 个答案:

答案 0 :(得分:0)

我认为您可以只使用一个公式,例如,此示例在abc30ded435wdfq345中检查30是否为

=IF(ISERROR(SEARCH(30,J16,1)),"No Match","Match")

不确定我是否完全了解您的问题。

答案 1 :(得分:0)

也许您可以将其用于代码中。它使用正则表达式。找到一个简单的数字是一个令人惊讶的冗长模式。

这只是寻找数字81。

Sub x()

Dim oRgx As Object, rCell As Range

Set oRgx = CreateObject("VBScript.RegExp")

With oRgx
    .Global = True
    .Pattern = "([^0-9]|^)81([^0-9]|$)"
    For Each rCell In ActiveSheet.UsedRange
        If .Test(rCell) Then MsgBox rCell.Address
    Next rCell
End With

End Sub

enter image description here