簡體   English   中英

在VBA中循環遍歷數組

[英]Looping through arrays in VBA

我試圖遍歷我擁有的數組,首先,我從第2行,第2列(大約1000行x 100列)開始的電子表格數據創建數組。 定義數組后,我想將每一列視為一個單獨的數據集,找到最大值和最大值的行號,然后將它們存儲在單獨的數組中。 當我運行此代碼時,它將返回一列0值。 它沒有給出任何錯誤,但是顯然不起作用,有什么建議嗎?

Public Maxindex() As Long

Public MaxVal() As Double

Sub ArrayOptimized()
'Uses arrays to call data from the sheet once then process it

    Dim dataset() As Variant
    Dim rows As Long
    Dim columns As Integer

    ReDim Maxindex(100)
    ReDim MaxVal(100)
    MaxVal(1) = 1

    rows = ShData.Cells(ShData.rows.Count, 1).End(xlUp).Row
    columns = ShData.Cells(1, ShData.columns.Count).End(xlToLeft).Column
    ReDim dataset(2 To rows, 2 To columns)
    dataset = ShData.Range(ShData.Cells(2, 2), ShData.Cells(rows, columns))
   'Check to sheet

    Sheet1.Range(Sheet1.Cells(1, 1), Sheet1.Cells(rows, columns)) = dataset


    For i = LBound(dataset, 2) To UBound(dataset, 2)

        For j = LBound(dataset, 1) To UBound(dataset, 1)
            If dataset(j, i) > MaxVal(i) Then
            MaxVal(i) = dataset(j, i)
            'Returns row index number in array for max val
            Maxindex(i) = j
            End If

        Next j

    Next i

    Sheet2.Range(Sheet2.Cells(1, 1), Sheet2.Cells(columns, 1)) = Maxindex

End Sub

默認情況下,Excel希望將一維數組放置在工作表上的行中 ,而不是列中,因此當您嘗試將其放置在列中時,會在每個單元格中獲得數組的第一個元素。

所有值都是零,因為您的一維數組是從零開始的,並且您沒有在循環中填充該插槽。

您可以使用轉置將數組“翻轉”到列中:

Sheet2.Range(Sheet2.Cells(1, 1), Sheet2.Cells(columns, 1)) = _
     Application.Transpose(Maxindex)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM