快速填充Array中的excel单元格

时间:2015-07-15 03:42:05

标签: excel vba excel-vba

我从外部数据工具生成数组,现在想要使用数组中的数据填充单元格。我写了以下代码。

With ThisWorkbook.Worksheets("Data")
   Lastrow = .Cells(.Rows.count, 2).End(xlUp).Row
   For i = LBound(Price) To UBound(Price)
   .Cells((Lastrow + 1), 1) = Price(i)
   .Cells((Lastrow + 1), 2) = Quantity(i)
   Lastrow = Lastrow + 1
   Next i
End With

所有数组长度相同,我有大约25个奇数阵列可供使用。代码工作正常,但我面临的问题是速度。我花了大约5-6个小时来填充一次,大约3000个阵列的长度。请建议您最好的方式。谢谢。

4 个答案:

答案 0 :(得分:1)

With ThisWorkbook.Worksheets("Data")
   NextRow = .Cells(.Rows.count, 2).End(xlUp).Row + 1
   num = UBound(Price) - LBound(Price)
   .Range(.Cells(NextRow, 1), .Cells(NextRow + num, 1)) = Application.Transpose(Price)
   .Range(.Cells(NextRow, 2), .Cells(NextRow + num, 2)) = Application.Transpose(Quantity)
End With

答案 1 :(得分:1)

要按M列填充N行范围,请将数据放入相同大小的二维数组中,然后将该数组指定给该范围的Value属性。

ReDim varValues(1 To lngRowCount, 1 To lngColCount)

或者

ReDim varValues(0 To lngRowCount - 1, 0 To lngColCount - 1)

我认为你可以处理填充数组。然后:

Set rngTheRange = 'I presume you can handle this, too
rngTheRange.Value = varValues

这是一个使用此技术用值0到N-1填充当前选择的示例,其中N是选择中的单元格数:

Option Explicit

Public Sub X()
    Dim rngCurrent As Range

    Dim lngRows As Long
    Dim lngCols As Long

    Dim lngR As Long
    Dim lngC As Long

    Dim varValues() As Variant

    Set rngCurrent = Selection

    lngRows = rngCurrent.Rows.Count
    lngCols = rngCurrent.Columns.Count

    ReDim varValues(0 To lngRows - 1, 0 To lngCols - 1) As Variant

    For lngR = 0 To lngRows - 1
        For lngC = 0 To lngCols - 1
            varValues(lngR, lngC) = lngR * lngCols + lngC
        Next
    Next

    rngCurrent.Value = varValues
End Sub

答案 2 :(得分:1)

根据您的问题,您有多个数组(25)具有不同的数据(例如,价格,数量,SomeOtherArray)。根据我上面的评论。

Option Explicit

Public Sub GetData()
Dim ws As Worksheet
Dim LastRow As Long
Dim arrPrice As Variant
Dim arrQty As Variant

Set ws = Sheets(3)
'-- starts at zero index
arrPrice = Array(50, 60, 70, 75)
arrQty = Array(250, 100, 50, 200)

'-- change columns as per your needs
LastRow = ws.Range("B" & ws.Rows.Count).End(xlUp).Row
'-- UBound + 1 is because the array starts at zero index above
ws.Range("B1").Offset(LastRow).Resize(UBound(arrPrice)+1).Value = Application.Transpose(arrPrice)
ws.Range("B1").Offset(LastRow, 1).Resize(UBound(arrQty)+1).Value = Application.Transpose(arrQty)

End Sub

enter image description here

答案 3 :(得分:1)

您可以将数组转储到工作表范围,非常简单:

range("A1:B5").value = myArray

您可以对话填充数组:

dim myArray as variant
myArray = range("A1:B5").value

我经常使用这种方法,我几乎不使用工作表上的数据,我更喜欢先把它带入数组,然后再使用数组。