我在 Sheet1 中有一個資料查找表,其中 A 列和 B 列中的所有名稱都是唯一的,因此 A 中的任何名稱都不存在于 B 中,反之亦然。但是,某些名稱可能包含特殊字符,例如連字符或破折號,例如 O'neil 或 Jamie-lee

我在 Sheet2 中有另一個資料表,其中我需要使用 D 列中的文本字串在 Sheet1(在 A 列或 B 列中)中找到匹配的名稱,然后在匹配時分配 sheet1 上該行的 Score 值在 Sheet2 列 E 中找到。
我在 E 列中輸入了匹配的分數值以證明我需要的結果。我不介意使用 VBA 或適用于 XL2010 的 Excel 公式

是否可以使用文本字串來查找單詞匹配項,因為我只看到了相反的內容,還是我看錯了?我只是似乎無處可去。
我經常更改代碼,現在試圖讓它作業,我想我有點迷茫,但這是我的代碼無法正常作業的當前狀態:
Sub TextSearch()
Dim LR As Long
LR = ThisWorkbook.Sheets("Sheet1").Range("A" & Rows.Count).End(xlUp).Row
Dim xLR As Long
xLR = ThisWorkbook.Sheets("Sheet2").Range("A" & Rows.Count).End(xlUp).Row
Dim oSht As Worksheet
Dim Lastrow As Long
Dim strSearch As String, Score As String
Dim aCell As Range
Dim i As Integer
Set oSht = Sheets("Sheet1")
Lastrow = oSht.Range("A" & Rows.Count).End(xlUp).Row
With Sheets("Sheet2")
'Loop from Lastrow to Firstrow (bottom to top)
For Lrow = xLR To 2 Step -1
'Get the value in the D column to perform search on
With .Cells(Lrow, "D")
If Not IsEmpty(.Value) Then
strSearch = .Value
Set aCell = oSht.Range("A1:B" & Lastrow).Find(What:=strSearch, LookIn:=xlValues, _
LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
MatchCase:=False, SearchFormat:=False)
For i = 2 To Lastrow
'Lookin column A on sheet1
If oSht.Cells(i, 1).Value = aCell Then
Score = oSht.Cells(i, 1).Offset(0, 2).Value
Sheets("Sheet2").Cells(Lrow, 4).Offset(0, 1).Value = Score
'Lookin Column B on sheet1
ElseIf oSht.Cells(i, 2).Value = aCell Then
Score = oSht.Cells(i, 2).Offset(0, 1).Value
Sheets("Sheet2").Cells(Lrow, 4).Offset(0, 1).Value = Score
End If
Next i
End If
End With
Next Lrow
End With
End Sub
uj5u.com熱心網友回復:
這應該可以完成您嘗試使用字典的操作。它根據作業表 1 上的 A 列和 B 列創建鍵,并將它們的分數存盤為專案。
如果您在 Sheet 1 中有重復的名字,這不會失敗,但它只會與遇到的名字匹配。沒有足夠的資料來區分我可以看到的。
Sub findmatches()
Dim ws1 As Worksheet
Dim ws2 As Worksheet
Dim dict As Object
Dim i As Long
Dim lr As Long
Dim name As String
Set ws1 = Worksheets("Sheet1")
Set ws2 = Worksheets("Sheet2")
Set dict = CreateObject("Scripting.Dictionary")
With ws1
lr = .Cells(.Rows.Count, 1).End(xlUp).Row 'Getting last row
For i = 2 To lr
If Not dict.exists(.Cells(i, 1).Value) Then 'Checking if name is in dictionary
dict.Add .Cells(i, 1).Value, .Cells(i, 3).Value 'Adding name and score
End If
If Not dict.exists(.Cells(i, 2).Value) Then 'Checking if name is in dictionary
dict.Add .Cells(i, 2).Value, .Cells(i, 3).Value 'Adding name and score
End If
Next i
End With
With ws2
lr = .Cells(.Rows.Count, 4).End(xlUp).Row
For i = 2 To lr
name = Split(.Cells(i, 4).Value, " ")(0) 'Splitting the string into an array and taking the first element
If dict.exists(name) Then 'Checking if name is in dict
.Cells(i, 5).Value = dict(name) 'assigning score to Column 5
Else
.Cells(i, 5).Value = 0 'No name score = 0
End If
Next i
End With
End Sub
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/360114.html
標籤:擅长 vba excel-2010
