VBA跨年度考勤匹配时Find方法中断触发运行错误91
运行时错误91的直接触发原因
- 报错行的
myObj_emply或myObj_day如果找不到匹配值,会返回Nothing,直接调用.Row/.Column属性就会触发91错误。之前12月31日前的记录都能匹配到对应值,到2021年1月1日的日期因为格式不匹配Find失败,直接触发报错。 - 嵌套循环逻辑完全失效:原代码套了
For a = 8 To 36、For j = 8 To 15两层完全无意义的循环,还在循环内部手动执行i = i + 1,直接打乱了kintai_demo表的行遍历节奏,导致i跳行、越界,甚至把员工ID的查找范围带偏——每次Find方法会以上一次找到的单元格为起点继续搜索,搜几次就超出F8:F26的范围,返回Nothing。 - 查找配置缺失:Range.Find方法会保留上一次的查找参数,没有显式指定匹配规则的话,跨日期区域搜索时很容易返回意外结果;加上两边表的日期格式不统一(一边是真日期、一边是文本格式日期),哪怕显示内容一致也无法匹配。
修复后可直接运行的代码
Private Sub CommandButton1_Click() Dim wsDemo As Worksheet, wsTest As Worksheet Dim lastRowDemo As Long, i As Long Dim empDict As Object, dateDict As Object Dim empID As String, attendDate As Date, attendVal As Variant Dim targetRow As Long, targetCol As Long '直接绑定对应工作表,减少重复调用开销 Set wsDemo = ThisWorkbook.Sheets("kintai_demo") Set wsTest = ThisWorkbook.Sheets("kintai_test") '用字典预存员工ID、日期的位置映射,比反复调用Find效率高且无状态干扰 Set empDict = CreateObject("Scripting.Dictionary") Set dateDict = CreateObject("Scripting.Dictionary") '扫描kintai_test的员工ID区域F8:F26,存映射关系 For i = 8 To 26 If wsTest.Cells(i, "F").Value <> "" Then empDict(CStr(wsTest.Cells(i, "F").Value)) = i End If Next '扫描kintai_test的日期表头区域H6:AL6,存映射关系 For i = 8 To 38 'H列对应列号8,AL列对应列号38 If IsDate(wsTest.Cells(6, i).Value) Then dateDict(CDate(wsTest.Cells(6, i).Value)) = i End If Next '逐行遍历kintai_demo的有效考勤数据(从第2行开始,第1行为表头) lastRowDemo = wsDemo.Cells(wsDemo.Rows.Count, 1).End(xlUp).Row For i = 2 To lastRowDemo empID = CStr(wsDemo.Cells(i, 1).Value) attendVal = wsDemo.Cells(i, 3).Value '跳过格式非法的日期行 If Not IsDate(wsDemo.Cells(i, 2).Value) Then GoTo NextValidRow attendDate = CDate(wsDemo.Cells(i, 2).Value) '跳过无匹配的员工或日期行 If Not empDict.Exists(empID) Then GoTo NextValidRow If Not dateDict.Exists(attendDate) Then GoTo NextValidRow '直接定位交叉单元格填充值 targetRow = empDict(empID) targetCol = dateDict(attendDate) wsTest.Cells(targetRow, targetCol).Value = attendVal NextValidRow: Next i '清空对象引用 Set empDict = Nothing Set dateDict = Nothing Set wsDemo = Nothing Set wsTest = Nothing MsgBox "考勤数据填充完成" End Sub
使用注意事项
- 统一两张表的日期格式:把kintai_demo里的日期列、kintai_test里的表头日期列都设置成标准日期格式,避免文本格式的日期无法匹配。
- 移除原代码里无意义的两层嵌套循环,遍历源数据每一行填值一次的逻辑完全可以实现需求,还能避免循环计数器乱跳的问题。
- 如果后续坚持用Find方法实现查找,每次调用必须显式指定
LookIn:=xlFormulas、LookAt:=xlWhole、SearchOrder:=xlByRows参数,不能依赖VBA默认的查找配置,否则跨区域查找很容易返回Nothing触发报错。
内容的提问来源于stack exchange,提问作者psl
相关产品推荐
相关产品推荐

