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

Excel VBA代码报错:CommandButton填充表格时出现运行时错误91

解决VBA CommandButton填充结构化表格时的运行时错误91问题

嘿,我来帮你排查这个运行时错误91的问题!这个错误的核心原因很明确:当你的Find方法找不到任何匹配内容时,会返回Nothing(空对象),这时候你直接去访问它的.Row属性,自然就触发了"对象变量或With块变量未设置"的错误。

你的代码问题分析

你当前用rng.Find来定位表格的最后一行,但如果你的table1是空的(只有表头,没有任何数据行),Find就找不到任何带内容的单元格,返回Nothing,这时候执行.Row就会炸锅。而且其实对于Excel的结构化表格(ListObject),完全没必要自己手动找最后一行,用内置的方法会更安全高效。

最优解决方案:用ListObject内置方法添加新行

直接使用ListRows.Add方法来添加新数据行,不管表格是空还是已有数据,这个方法都能正确定位到表格末尾添加行,还会自动继承表格的格式和规则,代码也更简洁:

Private Sub CommandButton1_Click()
    Dim newRow As ListRow
    
    ' 给table1添加一行新的数据行
    Set newRow = ActiveSheet.ListObjects("table1").ListRows.Add(AlwaysInsert:=True)
    
    ' 给新行的列赋值,这里可以用列索引,用列名会更直观(比如newRow.Range("列名").Value)
    newRow.Range(1).Value = TextBox1.Text
    newRow.Range(2).Value = ComboBox1.Text
    
    ' 注意:如果TextBox3-5是数值类型,建议转换为对应数值格式,避免文本转数值的问题
    ' 整数用CLng,小数用CDbl,根据你的需求调整
    newRow.Range(3).Value = CDbl(TextBox3.Value)
    newRow.Range(4).Value = CDbl(TextBox4.Value)
    newRow.Range(5).Value = CDbl(TextBox5.Value)
End Sub

如果你坚持要用Find方法(需添加空值判断)

如果你还是想保留原有的思路,那必须先判断Find的返回结果是否为Nothing,处理空表格的情况:

Private Sub CommandButton1_Click()
    Dim rng As Range
    Dim LastRow As Long
    Dim findResult As Range
    
    Set rng = ActiveSheet.ListObjects("table1").Range
    Set findResult = rng.Find(What:="*", _
        After:=rng.Cells(1), _
        Lookat:=xlPart, _
        LookIn:=xlFormulas, _
        SearchOrder:=xlByRows, _
        SearchDirection:=xlPrevious, _
        MatchCase:=False)
    
    ' 判断是否找到有效结果
    If Not findResult Is Nothing Then
        LastRow = findResult.Row
    Else
        ' 没找到说明只有表头,新行就是表头的下一行
        LastRow = rng.Row ' 表头行的行号
    End If
    
    ' 给新行赋值
    rng.Parent.Cells(LastRow + 1, 1).Value = TextBox1.Text
    rng.Parent.Cells(LastRow + 1, 2).Value = ComboBox1.Text
    rng.Parent.Cells(LastRow + 1, 3).Value = CDbl(TextBox3.Value)
    rng.Parent.Cells(LastRow + 1, 4).Value = CDbl(TextBox4.Value)
    rng.Parent.Cells(LastRow + 1, 5).Value = CDbl(TextBox5.Value)
End Sub

额外建议:处理数值输入的错误

如果TextBox3-5是用来输入数值的,最好加上错误处理,避免用户输入非数值内容导致报错:

On Error Resume Next
newRow.Range(3).Value = CDbl(TextBox3.Value)
If Err.Number <> 0 Then
    MsgBox "请在TextBox3中输入有效的数值!"
    TextBox3.SetFocus
    Exit Sub
End If
On Error GoTo 0

内容的提问来源于stack exchange,提问作者Chris V.

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.29 08:52:47