2011-05-19 96 views
10

我寫了一個需要2維數組的宏,並將其「打印」到Excel工作簿中的等效單元格。Excel VBA函數將數組打印到工作簿

有沒有更好的方法來做到這一點?

Sub PrintArray(Data, SheetName, StartRow, StartCol) 

    Dim Row As Integer 
    Dim Col As Integer 

    Row = StartRow 

    For i = LBound(Data, 1) To UBound(Data, 1) 
     Col = StartCol 
     For j = LBound(Data, 2) To UBound(Data, 2) 
      Sheets(SheetName).Cells(Row, Col).Value = Data(i, j) 
      Col = Col + 1 
     Next j 
      Row = Row + 1 
    Next i 

End Sub 


Sub Test() 

    Dim MyArray(1 To 3, 1 To 3) 
    MyArray(1, 1) = 24 
    MyArray(1, 2) = 21 
    MyArray(1, 3) = 253674 
    MyArray(2, 1) = "3/11/1999" 
    MyArray(2, 2) = 6.777777777 
    MyArray(2, 3) = "Test" 
    MyArray(3, 1) = 1345 
    MyArray(3, 2) = 42456 
    MyArray(3, 3) = 60 

    PrintArray MyArray, "Sheet1", 1, 1 

End Sub 

回答

14

在相同主題的其他的答案,保持簡單

Sub PrintArray(Data As Variant, Cl As Range) 
    Cl.Resize(UBound(Data, 1), UBound(Data, 2)) = Data 
End Sub 


Sub Test() 
    Dim MyArray() As Variant 

    ReDim MyArray(1 To 3, 1 To 3) ' make it flexible 

    ' Fill array 
    ' ... 

    PrintArray MyArray, ActiveWorkbook.Worksheets("Sheet1").[A1] 
End Sub 
+0

對於OLE自動化的緣故,分配到'Range'實際上意味着分配給它的'.Value'。 – 2018-02-02 04:49:38

3

創建一個變體數組(最簡單的方法是通過讀取變量變量的等效範圍)。

然後填充數組,然後將數組直接分配給範圍。

Dim myArray As Variant 

myArray = Range("blahblah") 

Range("bingbing") = myArray 

變體數組將最終成爲2-D矩陣。

0

更優雅的方式是將整個陣列一次給:

Sub PrintArray(Data, SheetName, StartRow, StartCol) 

    Dim Rng As Range 

    With Sheets(SheetName) 
     Set Rng = .Range(.Cells(StartRow, StartCol), _ 
      .Cells(UBound(Data, 1) - LBound(Data, 1) + StartRow, _ 
      UBound(Data, 2) - LBound(Data, 2) + StartCol)) 
    End With 
    Rng.Value2 = Data 

End Sub 

但是要注意:它只能達到一大小約8,000個細胞的。然後Excel引發一個奇怪的錯誤。最大尺寸不是固定的,並且從Excel安裝到Excel安裝的差異很大。

0

您可以定義範圍,您的數組的大小,並用它的價值屬性:

Sub PrintArray(Data, SheetName As String, intStartRow As Integer, intStartCol As Integer) 

    Dim oWorksheet As Worksheet 
    Dim rngCopyTo As Range 
    Set oWorksheet = ActiveWorkbook.Worksheets(SheetName) 

    ' size of array 
    Dim intEndRow As Integer 
    Dim intEndCol As Integer 
    intEndRow = UBound(Data, 1) 
    intEndCol = UBound(Data, 2) 

    Set rngCopyTo = oWorksheet.Range(oWorksheet.Cells(intStartRow, intStartCol), oWorksheet.Cells(intEndRow, intEndCol)) 
    rngCopyTo.Value = Data 

End Sub 
0

我的測試版本

Sub PrintArray(RowPrint, ColPrint, ArrayName, WorkSheetName) 

Sheets(WorkSheetName).Range(Cells(RowPrint, ColPrint), _ 
Cells(RowPrint + UBound(ArrayName, 2) - 1, _ 
ColPrint + UBound(ArrayName, 1) - 1)) = _ 
WorksheetFunction.Transpose(ArrayName) 

End Sub 
1

最短路徑:只需加入&個顯示元素,即,使用加入()函數加入數組元素作爲字符串,(,而不必使用循環或工作表型),例如:

MsgBox Join(arrayName, ",") 

'Above will display array elements as a single string separated by comma (a,b,c). 
相關問題