【问题标题】:Runtime error 91 when assigning array to table with single row将数组分配给单行表时出现运行时错误 91
【发布时间】:2023-02-20 21:47:07
【问题描述】:

我首先将一个表数据主体范围分配给一个有效的数组arr = tbl.DataBodyRange

将数组分配回表时,tbl.DataBodyRange = arr 适用于行数大于一的任何数组。

当数组只有一行时,我得到

运行时 91 错误:“未设置对象变量或 With 块变量”。

我无法共享原始文件。

【问题讨论】:

  • tbl 可能没有 .DataBodyRangeDebug.Print tbl.DataBodyRange Is Nothing 在立即窗口中返回什么?

标签: arrays vba


【解决方案1】:

DataBodyRange 到数组

语法错误

  • 当你使用Dim arr As Variant时,你允许arr变成任何东西(在这种情况下它变成Nothing)。当你再使用arr = tbl.DataBodyRange时,仍然没有报错。

良好的语法

  • 如果你使用

    Dim arr() As Variant
    

    相反,arr 只能传递一个数组。

  • 如果你使用

    arr = tbl.DataBodyRange.Value
    

    相反,如果范围是Nothing,则会发生错误。如果范围是一个单元格,则会发生错误。

代码

Option Explicit

Sub TableData()
    
    ' e.g.
    Dim tbl As ListObject
    Set tbl = ThisWorkbook.Worksheets("Sheet1").ListObjects("Table1")
    
    Dim rg As Range: Set rg = tbl.DataBodyRange
    
    ' Prevent
    ' "Run-time error '91': Object variable or With block variable not set"
    ' when the table is empty.
    If rg Is Nothing Then
        MsgBox "The table is empty.", vbExclamation
        Exit Sub
    End If
    
    Dim Data() As Variant
    
    ' Prevent
    ' "Run-time error '13': Type mismatch"
    ' when the range is just one cell.
    If rg.Rows.Count * rg.Columns.Count = 1 Then ' one cell
        ' Note that this is only possible if the table has just one column.
        ReDim Data(1 To 1, 1 To 1): Data(1, 1) = rg.Value
    Else ' multiple cells
        Data = rg.Value
    End If
    
    ' Do your thing... e.g., increase each number in the first column by 1:
    
'    Dim cValue As Variant
'    Dim r As Long
'
'    For r = 1 To UBound(Data, 1)
'        cValue = Data(r, 1)
'        If VarType(cValue) = vbDouble Then ' is a number
'            Data(r, 1) = cValue + 1
'        End If
'    Next r
    
    rg.Value = Data
    
End Sub

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-05
    • 1970-01-01
    • 1970-01-01
    • 2020-11-03
    • 1970-01-01
    • 2011-09-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多