使用VBA将值插入excel表的正确方法是什么?

时间:2012-08-22 21:24:53

标签: arrays vba excel-vba insert listobject

我需要能够使用VBA代码在excel中的空表中插入一大组值。 这是代码到目前为止的工作方式。

首先,用户将值输入到用户表单中。然后代码清除表格,然后根据代码中已有的查找条件找到一系列数字。检索到的数据全部包含在单个列中,并像数组一样存储。

从这里开始,我需要将所有值放在表中的某个列(Policy#)中,从而将表行扩展为检索数据集中的许多行。 (如果需要,我确实将计数单独存储为“AC”)我要插入的列标题是“Policy#”。

请记住,代码当前表中只有一个空行,如何正确插入数据?我试过了

 range("commissionstatement[Policy #]").value = Als

但这不起作用。顺便提一下,Als是一系列价值观。通常要插入数组,我必须插入一个大小相等的范围,这就是我将行数作为AC的原因。

我也尝试使用range("commissionstatement").listobject.listrows,但这也不起作用。

有什么建议吗?在我实际将数据放入那里之前,我是否需要在表格中插入一些行等于我添加的数据...

range("commissionstatement").listobject.listrows.add ()

然后插入数据?

如果需要更多信息,请与我们联系。谢谢!

2 个答案:

答案 0 :(得分:6)

假设您使用的是Excel 2010,请尝试此操作(可能不适用于早期版本的Excel)

Sub AddToList()
    Dim lo As ListObject
    Dim ws As Worksheet
    Dim Als() As Variant
    Dim rng As Range

    Set ws = ActiveSheet

    ' Get reference to table
    Set lo = ws.ListObjects("MyTable")  ' <--- Update this with your table name

    If lo.InsertRowRange Is Nothing Then
        ' List already has data
        Set rng = lo.ListRows.Add.Range
    Else
        ' List is empty
        Set rng = lo.InsertRowRange
    End If

    '  *** Remove one of these two lines ***
    ' If Als is a 1 dimensional array
    rng.Cells(1, lo.ListColumns("Policy #").Index).Resize(UBound(Als) - LBound(Als) + 1, 1) = Application.Transpose(Als)

    ' If Als is 2 dimensional array (1 to rows, 1 to 1)
    rng.Cells(1, lo.ListColumns("Policy #").Index).Resize(UBound(Als, 1), 1) = Als
End Sub

答案 1 :(得分:0)

这对我有用。我还用数组中的数据填充空ListObject。为此,数组matriu必须是二维数组。

Dim matriu() As Variant
Dim ls As ListObject

Set ls = Hoja1.ListObjects(1)

' Retrieve data
matriu = Hoja1.Range("Origen")

' Erease all rows of the ListObject, if needed
ls.DataBodyRange.Delete

' This line is needed in order for the next line 
' not to throw an error if the listobject is empty.
ls.ListRows.Add

' Fill the ListObject with all data in one operation to reduce execution time    
Range(ls.DataBodyRange.Cells(1, 1), _
   ls.DataBodyRange.Cells(UBound(matriu, 1), UBound(matriu, 2))) = matriu