有关于EXCEL VBA代码求助,用表2的数据来搜索表1,并修改相关值,请大师指点,万分感谢!

现在我有三个表格分别为sheet1和sheet2和sheet3,现在以sheet2表格里的每行特定列单元格数值做为搜索条件,去搜索表1中的所有行,找到的话修改表1中所在行的时间,没有找到就把表2的相关数据写到表3中去,同时对话框提示。现在有一个问题,有很小一部分搜索条件值在表1中明明存在,但搜索不到,将表2的相关内容写到了表3,同是对话框弹出
sheet2代码如下:
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
Dim h, i, n, a
If MsgBox("是否以服务记录月表将当量表进行更新?", 1 + 32 + 256, "表单更新对话框") = 1 Then
For h = 2 To Sheet2.[A65536].End(xlUp).Row

For i = 2 To Sheet1.[A65536].End(xlUp).Row
If n = 0 Then
If Sheet2.Cells(h, 8) = Sheet1.Cells(i, 6) Then
Sheet1.Cells(i, 7) = Sheet2.Cells(h, 3)
n = 1
End If
End If

Next
If n = 0 Then
r = Sheet3.[A65536].End(xlUp).Row + 1
Sheet3.Cells(r, 1) = Sheet2.Cells(h, 3)
Sheet3.Cells(r, 2) = Sheet2.Cells(h, 5)
Sheet3.Cells(r, 3) = Sheet2.Cells(h, 6)
Sheet3.Cells(r, 4) = Sheet2.Cells(h, 7)
Sheet3.Cells(r, 5) = Sheet2.Cells(h, 8)
Sheet3.Cells(r, 6) = Sheet2.Cells(h, 9)
Sheet3.Cells(r, 7) = Sheet2.Cells(h, 10)
Sheet3.Cells(r, 8) = Sheet2.Cells(h, 11)
Sheet3.Cells(r, 9) = Now()
MsgBox "以下设备记录在当量表中没有,请及时添加相关当量信息!" & Chr(13) + Chr(10) & Chr(13) + Chr(10) & "设备编号:" & Cells(h, 8).Value & Chr(13) + Chr(10) & "设备单位:" & Cells(h, 9).Value & Chr(13) + Chr(10) & "服务人员:" & Cells(h, 11).Value
ElseIf n = 1 Then n = 0
End If

Next

MsgBox "此表中设备服务时间在设备当量表中最近维修时间更新完毕!"

End If
End Sub

表1为当量表,表2为服务记录表,请大师指点,在线急等,解决加分没得问题,万谢!

代码逻辑上没有问题.
如果sheet1的第7列没有重复值,那个嵌套的内循环改成range.find效率更高.

ps:有时候看似相同的内容实际不同,比如多了空格,或者数值和文本型数值...追问

非常感谢zipall.原因就在于当量表中列在复制是不知为何在数值(已设为文格式)最后面有部分的多了个空格。删掉那部分有空格的就好了,再次感谢!

因为刚接触VBA,代码写起来很嫩,数据一多的话,需要等将近五分钟,所以非常想优化结构,不知道用range.find能够快多少,能否请大师给个具体程序,急着交差,我加来慢慢研究,感谢!!

追答

Private Sub Worksheet_SelectionChange(ByVal Target As Range)
Dim h, i, r, a, b
If MsgBox("是否以服务记录月表将当量表进行更新?", 1 + 32 + 256, "表单更新对话框") 1 Then Exit Sub
i = Sheet2.[A65536].End(xlUp).Row
a = Sheet2.Range("a1:k" & i).Value
With Sheet3
r = .[A65536].End(xlUp).Row
For h = 2 To i
Set b = Sheet1.Columns(6).Find(a(h, 8))
If b Is Nothing Then
r = r + 1
.Cells(r, 1) = a(h, 3)
.Cells(r, 2) = a(h, 5)
.Cells(r, 3) = a(h, 6)
.Cells(r, 4) = a(h, 7)
.Cells(r, 5) = a(h, 8)
.Cells(r, 6) = a(h, 9)
.Cells(r, 7) = a(h, 10)
.Cells(r, 8) = a(h, 11)
.Cells(r, 9) = Now()
MsgBox "以下设备记录在当量表中没有,请及时添加相关当量信息!" & vbCrLf & vbCrLf & "设备编号:" & a(h, 8) & vbCrLf & "设备单位:" & a(h, 9) & vbCrLf & "服务人员:" & a(h, 11)
Else
Sheet1.Cells(b.Row, 7) = a(h, 3)
End If
Next
End With
MsgBox "此表中设备服务时间在设备当量表中最近维修时间更新完毕!"
End Sub

温馨提示:答案为网友推荐,仅供参考
相似回答