You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用VBA的Intersect函数时触发错误91,如何解决?

VBA Intersect函数错误91的解决办法

错误原因

错误91是对象变量未设置,根源是调用Intersect时传入的参数逻辑错误:

  • newcttnbr是单个单元格(位于工作表By的ByLastRow行第1列),你用newcttnbr(1, i)的写法是基于该单元格的相对引用,无法正确定位到newcttnbr所在行的第i列单元格,导致Intersect返回Nothing,后续访问.Value触发错误。
  • 你的需求是取newcttnbr所在的行与By.Cells(2, i)所在的列的交叉单元格,应该直接引用整行和整列执行相交操作。

修正后的代码

Sub NvxDetail()
    Dim Ax As Worksheet: Set Ax = Workbooks("MODÈLE DE PROPOSITION DE CONTRAT DE SOUS-TRAITANCE.").Worksheets("Proposition de contrat")
    Dim By As Worksheet: Set By = Workbooks("Suivi contrat fact").Worksheets("Détail")
    Dim last_row As Integer: last_row = Ax.Cells(Ax.Rows.Count, 3).End(xlUp).Row
    Dim arng As Range: Set arng = Ax.Range(Ax.Cells(13, 1), Ax.Cells(last_row, 1))
    Dim ByLastRow As Long: ByLastRow = By.Cells(By.Rows.Count, 1).End(xlUp).Offset(1).Row
    Dim newcttnbr As Range: Set newcttnbr = By.Cells(ByLastRow, 1)
    
    Ax.Range("C12").Copy
    newcttnbr.PasteSpecial xlPasteValues
    Application.CutCopyMode = False
    
    Dim targetCell As Range
    For i = 4 To 104
        For Each c In arng
            If By.Cells(2, i).Value = c.Value Then
                Set targetCell = Intersect(newcttnbr.EntireRow, By.Cells(2, i).EntireColumn)
                If Not targetCell Is Nothing Then
                    targetCell.Value = c.Offset(0, 5).Value
                End If
                Exit For
            End If
        Next
    Next
End Sub

关键修改点

  • 替换Intersect(newcttnbr(1, i), By.Cells(2, i))为Intersect(newcttnbr.EntireRow, By.Cells(2, i).EntireColumn),精准定位行与列的交叉单元格。
  • 新增targetCell变量存储相交结果,先判断Not targetCell Is Nothing再赋值,避免因相交无效触发错误。
  • 修正By.Cells(Rows.Count, 1)为By.Cells(By.Rows.Count, 1),明确引用工作表By的行数,避免依赖活动工作表。
  • 移除无意义的ActiveCell.Select,减少冗余操作。

内容的提问来源于stack exchange,提问作者salifgotem

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.17 07:35:19