背景:
我有一张带有两张纸的excel文件,即' sheet1'和' sheet2'。这两张表都有相同的标题。
Sheet1-标题从columnB开始,而Sheet2-从columnA开始。
第一个标题(在两个表格中)都是唯一标识。
各个工作表中的两列都有一个值数组
问题:
如何使用VBA搜索sheet1(columnB)中是否存在sheet2(columnA)中的值。?
我的理论程序:
循环直到UID在' Sheet1'是空的
5.1一些操作
6.1一些操作
循环结束
请指导我如何进行此搜索活动。
提前致谢!
答案 0 :(得分:0)
你可以从这样的事情开始:
Sub Test()
Dim AlastRow As Integer
Dim Blastrow As Integer
With ThisWorkbook.Worksheets("Sheet1")
Blastrow = .Cells(.Rows.Count, "B").End(xlUp).Row
End With
With ThisWorkbook.Worksheets("Sheet2")
AlastRow = .Cells(.Rows.Count, "A").End(xlUp).Row
End With
Dim ra As Range
Dim rb As Range
With ThisWorkbook
Set ra = .Worksheets("Sheet1").Range("A1", "A" & AlastRow)
Set rb = .Worksheets("Sheet2").Range("B1", "A" & AlastRow)
End With
For Each cellb In rb.Cells
For Each cella In ra.Cells
If cella.Value = cellb.Value Then
'Found match, do stuff
Else
'Did not found match do stuff too
End If
Next
Next
End Sub
答案 1 :(得分:0)
您可以使用字典来执行此操作。使用字典意味着您只需读取sheet1中的值,而不是sheet2中的每个值。
Sub CompareColumns()
Dim dict As Object
Set dict = CreateObject("Scripting.dictionary")
Dim sheet1 As Worksheet, Sheet2 As Worksheet
Set sheet1 = ThisWorkbook.Worksheets("Sheet1")
Set Sheet2 = ThisWorkbook.Worksheets("Sheet2")
' Read values from sheet1 to dictionary
Dim lastRow As Long
lastRow = sheet1.Cells(sheet1.Rows.Count, 1).End(xlUp).Row
Dim i As Long
For i = 1 To lastRow
' Store value to dictionary
dict(sheet1.Cells(i, 1).Value) = 1
Next
' Read from sheet2 and check if each value exists
lastRow = Sheet2.Cells(Sheet2.Rows.Count, 2).End(xlUp).Row
For i = 1 To lastRow
' Check if value exists in dictionary
If dict.exists(Sheet2.Cells(i, 2).Value) Then
' found
Else
' not found
End If
Next
End Sub