find匹配的ID时出错

我有两个工作表sheet1,sheet2

对于sheet1,我有一个始终以4开头的id,我在sheet2中查找这个ID,并将相应的名称复制回到sheet1。

ID总是8位长。

在这期间,我有一个特殊情况,身份证有一些特殊的字符和字符。 例如:41017734_dr_bad; 代码在这种情况下失败。 我没有认出第一个8,并没有粘贴在另一张纸上。

有人可以build议如何克服这一点? 我有一个想法,我们可以使用whilcard和strlen函数。 但碰到如何在代码中使用。

Sub match() Dim sh1 As Worksheet, sh2 As Worksheet Dim cell As Range, cell2 As Range, lstcl As Variant, lstcl2 As Variant, rgFnd As Variant Dim n As Double, ID As String Set sh1 = ThisWorkbook.Sheets("S") Set sh2 = ThisWorkbook.Sheets("P") ID = "4" lstcl = sh1.Range("N10000").End(xlUp).Row lstcl2 = sh2.Range("L10000").End(xlUp).Row 'comparing columns N and L in both sheets For Each cell In sh2.Range("L5:L" & lstcl2) For n = 5 To lstcl If cell = sh1.Range("N" & n) Then 'the cell in column M next to the matching cell is equal to the 4xxxxxxx number cell.Offset(0, 1) = sh1.Range("N" & n) 'the next cell in column N is equal to the A2C number in column A cell.Offset(0, 2) = cell.Offset(0, -11) End If Next Next 'test that each cell in the first sheet corresponds to the located results in the second sheet _ 'and pastes back the A2C number, using the Range.Find function For Each cell2 In sh1.Range("N5:N" & lstcl) If Left(cell2, 1) = ID Then Set rgFnd = sh2.Range("M5:M" & lstcl2).Find(cell2.Value) If Not rgFnd Is Nothing Then cell2.Offset(0, 1) = sh2.Range(rgFnd.Address).Offset(0, 1) End If End If Next End Sub 

这是我的ID在N列中的sht1中查找的方式。它具有以4开头(N列)的B2C和ID的ID。 这是sheet2中ID的样子,一列包含B2C(列A)的ID,另一列列出id为4(列L)

结果看起来像这样,我查看N列中的ID并将它们与sheet2中包含4的列L相匹配,然后从sheet2中拉出相应的ID并粘贴到下一列。我已经把spl条件突出显示为红色,因为如果我们注意到数字是相同的,由于最后的字符串,它不被识别。我想检查第一个8位,如果他们匹配,那么它应该能够按照下面的代码。如果我们可以在我的代码中添加一行并可以得到结果,那将会很棒。

尝试这个

 Sub match() Dim sh1 As Worksheet, sh2 As Worksheet Dim cell As Range, cell2 As Range, lstcl As Variant, lstcl2 As Variant, rgFnd As Variant Dim n As Double, ID As String Set sh1 = ThisWorkbook.sheets("S") Set sh2 = ThisWorkbook.sheets("P") ID = "4" lstcl = sh1.Range("N10000").End(xlUp).Row lstcl2 = sh2.Range("L10000").End(xlUp).Row 'comparing columns N and L in both sheets For Each cell In sh2.Range("L5:L" & lstcl2) For n = 5 To lstcl a = Left(sh1.Range("N" & n), 8) If cell = a Then 'the cell in column M next to the matching cell is equal to the 4xxxxxxx number cell.Offset(0, 1) = a 'the next cell in column N is equal to the A2C number in column A cell.Offset(0, 2) = cell.Offset(0, -11) End If Next Next 'test that each cell in the first sheet corresponds to the located results in the second sheet _ 'and pastes back the A2C number, using the Range.Find function For Each cell2 In sh1.Range("N5:N" & lstcl) If Left(cell2, 1) = ID Then Set rgFnd = sh2.Range("M5:M" & lstcl2).Find(cell2.Value) If Not rgFnd Is Nothing Then cell2.Offset(0, 1) = sh2.Range(rgFnd.Address).Offset(0, 1) End If End If Next End Sub