(VBA Excel)尝试从macros表中收集数据,错误91

所以我有两张工作簿,第一张包含一个人的名和姓,第二张包含用户名(人名的第一个名字和全名,例如:John Smith – > jsmith)。 第二张表在每个用户名右边的5列中都有信息,我需要收集这些信息并在第一张表上填上相应的名字。 现在运行结果如下:

Run-time error '91': Object variable or With block variable not set 

当它不在while循环中时,我得到了代码的主体。 所以我知道代码在input单个单元时工作。 但是,我的可变单元格的实现将不会与它的行为。 代码如下:

 Sub Macro() ' set up counter Dim rownum As Long rownum = 1 Do While rownum < 273 Dim cellA As String Dim cellB As String Dim cellC As String ' change cells depending on current rownum cellA = "A" & CStr(rownum) cellB = "B" & CStr(rownum) cellC = "C" & CStr(rownum) Dim rngA As String Dim rngB As String Dim rngAB As String ' select sheet and collect first initial of first name and full last name Sheets("Sheet1").Select first = Left(Range(cellA).Value, 1) last = Range(cellB).Value searchname = first & last ' select sheet with info and find the row with username Sheets("Sheet2").Select ' ***this is where the issue is*** Cells.Find(What:=searchname, LookIn:=xlFormulas, LookAt _ :=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:= _ False, SearchFormat:=False).Activate ' ***this is where the issue is*** ' copy the info and paste it into the first sheet Application.CutCopyMode = False ActiveCell.Offset(, 1).Resize(1, 5).Copy Sheets("Sheet1").Select Range(cellC).Select ActiveSheet.Paste rownum = rownum + 1 Loop End Sub 

如果有人能告诉我我做错了什么,或者知道一个更清洁的方法,那就太好了。

问题是你正在尝试使用.Find()的返回值,而不检查是否真的在这一行上find任何东西:

  Cells.Find(What:=searchname, LookIn:=xlFormulas, LookAt _ :=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:= _ False, SearchFormat:=False).Activate 

如果.Find()没有返回任何东西,那么没有任何东西可以被激活 – 因此错误91。

尝试保存返回到variables,检查是否是什么,然后做任何你需要做的基础上,如果你find或不是:

 Dim result As Range Set result = Cells.Find(What:=searchname, LookIn:=xlFormulas, LookAt _ :=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:= _ False, SearchFormat:=False) If Not result Is Nothing Then result.Activate 'Found code Else 'Not found code. End If 

也就是说,通常应避免使用.Activate.Select – 而是直接抓取引用并使用对象,而不是使用全局Active对象。

您通常不需要使用复制和粘贴,并可以直接设置值。 您也可以使用工作表的.Cells属性来避免创build单元格string。

 Sub test() Dim i as Integer Dim rownum As Long Dim rng As Range rownum = 1 Do While rownum < 273 'collect first initial of first name and full last name first = Left(Sheets("Sheet1").Cells(rownum, 1).Value, 1) last = Sheets("Sheet1").Cells(rownum, 2) searchname = first & last 'copy values to first sheet Set rng = Sheets("Sheet2").Cells.Find(What:=searchname, MatchCase:=False) For i = 1 To 5 Step 1 Sheets("Sheet1").Cells(rownum, i + 2).Value = rng.Offset(, i).Value Next i rownum = rownum + 1 Loop End Sub