将数据数组项分配给范围值的最快方法是什么

时间:2017-11-17 14:17:03

标签: excel vba ado

我正在为SQL服务器数据库开发一个excel客户端。

当我从数据库中选择数据到客户端时,记录会保存在数组中。然后注入这些阵列"使用变量数组到Excel工作表。

这种技术比分配单个单元格值要快得多,但在某些特定情况下似乎失败了。

当数据值为vbNullString时,未分配与该项对应的范围单元格。如果第一个项目是vbNullString,则最糟糕的是,没有项目保存到范围内。 我的猜测是vbNullString被转换为null作为变体而变体数组的维度是错误的。

还有其他解释吗?

例如

ByRef loTable As ListObject,
ByRef sItems() As String

是执行以下代码的子参数 loTable是一个Excel表(ListObject),并且我想要分配给Excel Table loTable

的范围的数据
Dim lCount as Long
Dim vItems() as Variant
lCount = UBound(sItems)-LBound(sItems)+1
'size vItems as a 2D array - required to fetch a range
If (lCount > 0) Then ReDim vItems(1 To lCount, 1 To 1)
'copy string to variant
Dim i As Integer
For i = LBound(sItems) To UBound(sItems)
    vItems(i, 1) = sItems(i)
Next i
Dim olrs As ListRows
Set olrs = loTable.ListRows
With loTable
    If (lCount > 0) Then
        If (Not (.DataBodyRange Is Nothing)) Then .DataBodyRange.Delete
        olrs.Add
        If (lCount = 1) Then
            olrs(olrs.Count).Range.Cells(1, 1).Value = sItems(LBound(sItems))
        Else
            .DataBodyRange.Resize(lCount, 1).Value = vItems
        End If
    Else
        .DataBodyRange.Delete
    End If
End With 'loTable

我提出了一个问题:你是否尝试过这样一个范围(表)的值赋值以及如何处理数组中的空项以进行快速赋值。 循环遍历数组项并逐个添加只需要永远。

1 个答案:

答案 0 :(得分:2)

这样的事情有帮助吗?

'Declarations section
Private Const gsPROVIDER as String = [Provider]
Private Const gsDATA_SOURCE as String = [Source]
Private Const gsINITIAL_CATALOG as String = [Catalog]
Private Const gsUSER_ID as String = [User ID]
Private Const gsPASSWORD as String = [Password]

Private Sub Test
    Dim rsData As Object
    Dim sConnect As String
    Dim sSQL As String

    sConnect = "Provider=" & gsPROVIDER & _
               "Data Source=" & gsDATA_SOURCE & _
               "Initial Catalog=" & gsINITIAL_CATALOG & _
               "User ID=" & gsUSER_ID & _
               "Password=" & gsPASSWORD
    sSQL = 'SQL in a string

    Set rsData = CreateObject("ADODB.Recordset")
    rsData.Open sSQL, sConnect

    If Not rsData.EOF Then
        Worksheets(1).ListObjects(loTable).DataBodyRange.CopyFromRecordset rsData
    Else
        MsgBox "No data found!", vbCritical, "Error!"
    End If

    rsData.Close
    Set rsData = Nothing
End Sub