[英]VBA to check if values from one sheet are found in another sheet
我想開發一個宏來檢查工作表中一列的值是否在另一工作表的列中作為子字符串找到。
因此,我想檢查第一列的每個單元格,如果它不為空,則將其與第二張表的第1列和第3列的每個單元格進行比較。
為此,我使用了“ for each”循環,然后使用了“ for”循環,i從1到Rows.Count。
這是棘手的問題,因為我不確定這是否是正確的方法。 另外,用於檢查是否以子字符串形式找到值的instr()函數的參數似乎不匹配,因為在嘗試運行代碼時出現“類型不匹配”錯誤。
Sub test()
Set Wks1 = Worksheets("Sheet1")
Set Wks2 = Worksheets("Sheet2")
Dim i As Long
Dim rng As Range, cell As Range
Set rng = Wks1.Range("C3:O69")
For Each cell In rng
If Not (IsEmpty(cell.Value)) Then
For i = 1 To Wks2.Rows.Count
If (InStr(Cells(i, 1), cell.Value, 1) <> 0) Or (InStr(Cells(i, 3), _
cell.Value, 1) <> 0) Then
Cells(i, 4) = "String contains substring"
End If
Next i
End If
Next cell
End Sub
那應該工作
Sub test()
Dim i As Long
Dim rng As Range, cell As Range
Dim lastRow as Long
Set Wks1 = Worksheets("Sheet1")
Set Wks2 = Worksheets("Sheet2")
Set rng = Wks1.Range("C3:O69")
lastRow = Wks2.Cells(Rows.Count, 1).End(xlUp).row
For Each cell In rng
If Not (IsEmpty(cell.Value)) Then
For i = 1 To lastRow
With Wks2
If (InStr(.Cells(i, 1), cell.Value) <> 0) Or (InStr(.Cells(i, 3), cell.Value) <> 0) Then
.Cells(i, 4) = "String contains substring"
End If
End With
Next i
End If
Next cell
End Sub
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.