Sub myQuery()
Dim ws1 As Worksheet, ws2 As Worksheet, rng1 As Range, rng2 As Range
Dim cell1 As Range, cell2 As Range
Dim date1 As Date, date2 As Date, value1 As Double, value2 As Double
Dim i As Integer, lRow As Integer, lCol As Integer
Dim arr(), IsValid As Boolean
Dim dic As Object
Set ws1 = ThisWorkbook.Sheets("Sheet1")
Set ws2 = ThisWorkbook.Sheets("Sheet2")
'//原数据区域
With ws1
lRow = .Cells(.Rows.Count, 2).End(xlUp).Row
lCol = .Cells(2, .Columns.Count).End(xlToLeft).Column
Set rng1 = .Range(.Cells(3, 2), .Cells(lRow, lCol))
End With
'//查找区域
With ws2
lRow = .Cells(.Rows.Count, 5).End(xlUp).Row
lCol = .Cells(2, .Columns.Count).End(xlToLeft).Column
Set rng2 = .Range(.Cells(3, 5), .Cells(lRow, lCol))
End With
'//循环原数据区域每一行
For Each cell1 In rng1.Columns(1).Cells
date1 = cell1.Value
value1 = cell1.Offset(0, 1).Value
cell1.Offset(, 2) = ""
'//循环查找区域每一行
For Each cell2 In rng2.Columns(1).Cells
date2 = cell2.Value
value2 = cell2.Offset(, 1).Value
IsValid = False
'//如果日期相同
If date1 = date2 Then
'//与原数相比,如果两个数相差1%
If Abs((value1 - value2) / value1) <= 0.01 Then
'//根据matchType判断当前记录是否符合要求
If matchType = "大于" Then
If value1 < value2 Then
IsValid = True
End If
ElseIf matchType = "小于" Then
If value1 >= value2 Then
IsValid = True
End If
Else
IsValid = True
End If
If IsValid Then
'//找到第一个符合条件的值,填入目标单元格
If Val(cell1.Offset(, 2)) = 0 Then
cell1.Offset(, 2) = value2
'//如果已取到数,取与原数相差更小的
ElseIf Abs(cell1.Offset(, 2) - value1) > Abs(value2 - value1) Then
cell1.Offset(, 2) = value2
End If
End If
End If
End If
Next
Next
End Sub