如何正确设置excel vb代码的if条件Cells.Find? 还有2个问题

我有这个问题,并在Excel上回答了代码如何使用库search和replace列上的string 。 我有三(3)个问题。

  1. 运行时错误13,如何确定如果findRange发现了什么?
  2. 这是findfindRange的正确方法吗?
  3. 如何在活动页面上添加“未find”?

从:

在这里输入图像说明

至: – 这是我想要完成的。

在这里输入图像说明

vba代码如下:

Sub FindAndReplace() ' FindAndReplace Macro ' @author Louie Miranda ' Ability to find the range of ids against another worksheet ' and insert the name on the main sheet, one issue is if the value does not exist Dim findRange as Object ' Loop over the current worksheet For Each c In Worksheets("RECORDS").Range("A3:A7").Cells ' Go to Agents sheet Sheets("AGENTS").Select ' Do a search Columns("B:B").Select ' Q1: RUN-TIME ERROR 13, HOW TO DETERMINE IF findRange HAS FOUND SOMETHING? Set findRange = Cells.Find(What:=c, After:=ActiveCell, LookIn:=xlFormulas, LookAt _ :=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:= _ False, SearchFormat:=False).Activate ' Determine if the find has something ' Q2: IS THIS THE CORRECT WAY TO FIND THE findRange? If findRange Is Nothing Then MsgBox "not found" ' Back to records sheet Sheets("RECORDS").Select 'Range(c.Address).Offset(0, 1).Select 'ActiveSheet.Paste ' Q3: HOW TO ADD A "NOT FOUND" ON THE ACTIVE SHEET PAGE? Else Application.CutCopyMode = False ' Choose beside the column to copy ActiveCell.Offset(rowOffSet:=0, columnOffset:=-1).Activate Selection.Copy ' Back to records sheet Sheets("RECORDS").Select ' Copy the agent name to RECORDS sheet Range(c.Address).Offset(0, 1).Select ActiveSheet.Paste End If Next c End Sub 

任何帮助深表感谢。

亲切的问候

我更新了你的代码。 这应该现在工作。

 Sub FindAndReplace() Dim findRange As Range Dim c As Range ' Loop over the "RECORDS" worksheet For Each c In Worksheets("RECORDS").Range("A3:A7").Cells 'Set findRange in "AGENTS" sheet With Worksheets("AGENTS") Set findRange = .Cells.Find(What:=c.Value, After:=.Cells(1, 1), LookIn:=xlFormulas, LookAt _ :=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:= _ False, SearchFormat:=False) End With If Not findRange Is Nothing Then 'if found then Sheets("RECORDS").Cells(c.Row, c.Column + 1) = Sheets("AGENTS").Cells(findRange.Row, findRange.Column - 1).Value Else 'if not found then Sheets("RECORDS").Cells(c.Row, c.Column + 1) = "Not Found" End If Next c