我想创建一个Excel VBA宏来查找" a123Apple873hhh"并且知道我只是想找" Apple"。
在示例中更容易理解:
在sheet1上,我有一个带有名称及其代码的固定表数组:
Column A---Column B
12------ --Banana
20-------- Apple
44-------- Orange
在sheet2上,我有我想要的东西:
Column A----------Column B
.......... -------ds$$Orange1111aaa
.......... -------22Apple999
.......... -------22Watermelon
.......... -------9q9Orange7ab
etc...
我想要一个查看sheet2 / B列的VBA,找到sheet1 / B列上的名称,并在sheet2 / Column A上给出其代码。 所以,最终的结果是:
Column A------Column B
44 -----------ds$$Orange1111aaa
20 -----------22Apple999
*BLANK* ------22Watermelon
44 -----------9q9Orange7ab
etc...
我的代码无法正常工作,因为它只是找到了确切的结果:
Sub FindCode()
Const COLUMN As String = "E"
Dim i As Long
Dim iLastRow As Long
Dim cell As Range
Dim sh As Worksheet
With ActiveSheet
iLastRow = .Cells(.Rows.Count, COLUMN).End(xlUp).Row
For i = 6 To iLastRow
If .Cells(i, "E") = "" Then
.Cells(i, "A").Value = ""
Else
.Cells(i, "A").Value = Application.VLookup(.Cells(i, "E").Value, Range("etc!A:B"), 2, False)
End If
Next i
End With
End Sub
答案 0 :(得分:4)
我使用了您提供的完全相同的数据。 Sheet1看起来像这样:
Sheet2如下:
我使用了此代码
Sub SearchProduct()
Dim ws1 As Worksheet: Set ws1 = ThisWorkbook.Sheets(1)
Dim ws2 As Worksheet: Set ws2 = ThisWorkbook.Sheets(2)
Dim fruit As Range: Set fruit = ws1.Range("B2", ws1.Cells(ws1.Rows.Count, "B").End(xlUp))
Dim fruitCode As Range: Set fruitCode = ws2.Range("B2", ws2.Cells(ws2.Rows.Count, "B").End(xlUp))
Dim f As Range, s As Range
For Each s In fruit
For Each f In fruitCode
If InStr(s.Text, f.Text) <> 0 Then
s.Offset(0, -1).Value = f.Offset(0, -1).Value
GoTo SkipTheRest
End If
Next f
SkipTheRest:
Next s
End Sub
在Sheet2上产生了以下结果
一些限制如下:
Replace()
可以轻松修复此问题。 答案 1 :(得分:0)
这应该做:
Option Explicit
Sub main()
Dim fruitRng As Range, cell As Range, found As Range
Dim firstAddress As String
With Worksheets("Sheet1")
Set fruitRng = .Range("B1", .Cells(.Rows.Count, 2).End(xlUp)).SpecialCells(XlCellType.xlCellTypeConstants)
End With
With Worksheets("Sheet2")
With .Range("B1", .Cells(.Rows.Count, 2).End(xlUp)).SpecialCells(XlCellType.xlCellTypeConstants)
For Each cell In fruitRng
Set found = .Find(what:=WorksheetFunction.Trim(cell.Value), lookat:=xlPart, LookIn:=xlValues)
If Not found Is Nothing Then
firstAddress = found.Address
Do
found.Offset(, -1).Value = cell.Offset(, -1).Value
Set found = .FindNext(found)
Loop While found.Address <> firstAddress
End If
Next cell
.Offset(, -1).SpecialCells(xlCellTypeConstants, xlTextValues).ClearContents
End With
End With
End Sub