使用VBA在同一工作簿的工作表之间search值
背景:
我有一个excel文件,有两张纸,分别是'sheet1'和'sheet2'。 两张纸都有相同的标题。
Sheet1-header从columnB开始,从sheetA开始从Sheet2-开始。
第一个标题(在这两个表)是唯一的ID。
相应工作表中的列都有一组值
问题:
如何使用VBAsearchsheet2(columnA)中sheet2(columnA)中的值是否存在?
我的理论程序:
循环直到“Sheet1”中的UID为空
- 转到“sheet2”
- 读取UID值
- 转到“sheet1”
- 在UID列中search读取的UID
- 如果find
5.1一些操作
- 如果没有find
6.1一些操作
循环结束
请指导我如何做这个search活动。
提前致谢!
您可以使用字典来做到这一点。 使用字典意味着您只读取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
你可以从这样的事情开始:
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