VBA 函数在 excel 2016 中返回数组时导致运行时错误 13,但在 office 365 中没有?

VBA function causing runtime error 13 while returning array in excel 2016 but not in office 365?

我有一个函数可以读取选项卡中的数据并将其 returns 作为一维数组:

Public Function OneDimension(arr)
    OneDimension = Application.Transpose(Application.Transpose(arr))
End Function

打开表单时调用函数:

Set actionDict = New Scripting.Dictionary
numArrCols = Data.Columns.Count - 1
ReDim arr(1 To numArrCols) 'empty array

For Each rw In Data.rows
    id = "" & rw.Cells(1).Value
    If Not actionDict.Exists(id) Then
        actionDict.Add id, New Collection 'new key: add key and empty collection
    End If
    actionDict(id).Add OneDimension(rw.Cells(2).Resize(1, numArrCols).Value) 'add the row value as 1D array
Next rw

数据如下所示:

user id name date answer amount comments completed helper
1 test,t 05/22/2022 yes 0.01 something No 144687

用公式

helper = user id & date

user id 是一个文本字段,date 存储为 mm/dd/yyyy,当我 运行 使用 Office 365 时它看起来很好,但是当我的老板 运行 它与 excel 2016 它给出了这个错误:

runtime error 13 type mismatch

在调试器中使用这个:

可能是什么原因造成的?

One-Row 一维数组的范围

  • 为什么使用功能有限的 one-liners?它们更短,但通常不会更快。

  • 在你的子程序中,你可以使用:

    actionDict(id).Add OneDaRow(rw.Cells(2).Resize(1, numArrCols))
    

函数

Function OneDaRow(ByVal RowRange As Range) As Variant
    
    Dim Data As Variant ' 2D one-based one-row array
    Dim c As Long
    
    With RowRange.Rows(1)
        c = .Columns.Count
        If c = 1 Then ' one cell
            ReDim Data(1 To 1, 1 To 1): Data(1, 1) = .Value
        Else ' multiple cells
            Data = .Value
        End If
    End With
        
    Dim Arr As Variant: ReDim Arr(1 To c) ' 1D one-based array
    
    For c = 1 To c
        Arr(c) = Data(1, c)
    Next c
    
    OneDaRow = Arr

End Function

功能测试

Sub OneDaRowTEST()
    Dim rg As Range: Set rg = Range("A1").CurrentRegion
    Debug.Print Join(OneDaRow(rg), vbLf)
End Sub