我已经编写了以下代码来自动搜索T5536值的搜索功能 它位于sheet1的A1单元格中,并将A1单元格值与sheet2中具有n个值的列进行比较。 当A1值T5536与Sheet2 A列中的值匹配时,它应该使用对应的ES或IS值更新Sheet1。 如果Sheet2中的ES值具有间接字或字符串,则它应更新sheet1中的IS值。
请找到相同的以下代码: -
Sub test()
Dim lrow As Long
Dim i, j As Variant
Dim ms, ws As Worksheet
Dim num, esr, isr,x As Long
Application.ScreenUpdating = False
Application.DisplayAlerts = False
Set ms = Worksheets("sheet1")
Worksheets("Sheet2").Activate
ms.Cells(2, 3) = ""
ms.Cells(2, 2) = ""
Set ws = Worksheets("Sheet2")
num = WorksheetFunction.Match("number", Range("1:1"), 0)
esr = WorksheetFunction.Match("ES", Range("1:1"), 0)
isr = WorksheetFunction.Match("IS", Range("1:1"), 0)
x = sheet2.cells(sheet2.rows.count,"A").end(xlup).row
FoundRange = ms.Range("A1")
For i = 2 To x
If ws.Cells(i, num) = FoundRange Then
Worksheets("sheet1").Activate
ms.Cells(2, 3) = ws.Cells(i, isr)
If ws.Cells(i, es) = "indirect" Then
ms.Cells(2, 2) = ws.Cells(i, is)
Else
ms.Cells(2, 2) = ws.Cells(i, es)
End If
End If
If ms.Cells(2, 2) <> "" Then
Exit For
End If
Next i
End Sub
当sheet2 A列中只有很少的值匹配时,以下代码将起作用并花费更少的时间,但如果sheet2中有n个值,则很难通过for循环完成任务,请帮我调整这段代码,以便非常快速地搜索值并更新相应的值。
我附上了可能有助于分析查询的图片。
答案 0 :(得分:1)
检查出来。您可以根据需要编辑此代码。
Sub loopExample()
Dim sh As Worksheet, ws As Worksheet
Dim LstRw As Long, Frng As Range
Dim rng As Range, c As Range, x
Set sh = Sheets("Sheet1")
Set ws = Sheets("Sheet2")
Set Frng = sh.Range("A1")
With ws
LstRw = .Cells(.Rows.Count, "A").End(xlUp).Row
Set rng = .Range("A2:A" & LstRw)
End With
For Each c In rng.Cells
If c = Frng Then
x = IIf(c.Offset(0, 1) = "indirect", 2, 1)
sh.Range("B2") = c.Offset(0, x)
End If
Next c
End Sub