增加一个变量用来判断是否找到就行了,修改后的代码如下,改过的语句用注释标出来了。
Private Sub Worksheet_Change(ByVal Target As Range)
'MsgBox
If Target.Address = "$A$1" Then
vl = Cells(Target.Row, Target.Column)
xr = Target.Row: xc = Target.Column
If Len(vl) = 0 Then Exit Sub ''空值退出
On Error Resume Next
x = ActiveSheet.Name
'MsgBox x
For Each Sh In ThisWorkbook.Sheets
If Sh.Name = x Then GoTo a_next
y = Sh.Name
'MsgBox y
Set sj = Worksheets(y)
ed = sj.[A65536].End(xlUp).Row
s=0 '新增语句
For i = 1 To ed
If sj.Cells(i, 1).Value = vl Then
Worksheets(x).Cells(xr, xc + 1) = sj.Cells(i, 2).Value
s=1 '新增语句
goto a_next '修改了原语句
End If
Next
if s=0 then msgbox "没找到!" '新增语句
a_next: Set sj = Nothing
Next
End If
End Sub
Private Sub Worksheet_Change(ByVal Target As Range)
'MsgBox
If Target.Address = "$A$1" Then
vl = Cells(Target.Row, Target.Column)
xr = Target.Row: xc = Target.Column
If Len(vl) = 0 Then Exit Sub ''空值退出
On Error Resume Next
x = ActiveSheet.Name
'MsgBox x
For Each Sh In ThisWorkbook.Sheets
If Sh.Name = x Then GoTo a_next
y = Sh.Name
'MsgBox y
Set sj = Worksheets(y)
ed = sj.[A65536].End(xlUp).Row
For i = 1 To ed
If sj.Cells(i, 1).Value = vl Then
Worksheets(x).Cells(xr, xc + 1) = sj.Cells(i, 2).Value
'如果执行到这一步,表示已找到,作个标志就行了
biaozhi=true
Exit For
End If
Next
a_next: Set sj = Nothing
Next
if biaozhi=false then msgbox "没找到!"
End If
End Sub
使用iserr()判断搜索的结果,没结果就弹出提示框呗