填充2维VBA阵列Excel

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了填充2维VBA阵列Excel相关的知识,希望对你有一定的参考价值。

enter image description here

我一直坚持创建并填充一个数组,该数组将每个lineitem存放在上面显示的行中,并按描述标题下列出的Acct对每个存款进行分类。下面列出了7列。(7 Col)

电子表格每天更新,excel电子表格中最多可以有50,000行,因此“For Next”循环不是最佳选择,因为在按照帐户编号填充数组后,下一步是按日期对存款进行年龄计算。今天的日期”。

我通过debug.print在即时窗口中得到一个结果,但每个Acct Number的amts没有正确加起来。我正在寻求帮助,看看是否有人对我未到达的地方有任何具体的想法。

Option Explicit
Option Compare Text
Option Base 1

Const MFGWholesale = 1628258400
Const DealerDirect= 8900504722
Const Retail = 8901054887

Sub AccumulativeSum()
Dim Dest As Range
Dim i As Integer, j As Integer
Dim ArrayMFG() As Variant, ArrayDD() As Variant, ArrayRetail() As Variant

Dim rcnt As Integer
Dim ws As Worksheet
Set ws = Worksheets("Trial")

'Turns off screen updating and auto calc to reduce process time
With Application
.ScreenUpdating = False
.Calculation = xlCalculationManual
End With

'unfilters if it's active BEFORE running the Array Process
If ws.FilterMode Then
    ws.ShowAllData
End If

rcnt = ws.Range("ColSeven").Rows.Count '<-- Initial Row Count of ColSeven Range
rCol = ws.Range("ColSeven").Value2 '< -- Value2 has it's advantages for arrays

'Resizing the Arrays
ReDim ArrayMFG(1 To rcnt, 1 To 7)
ReDim ArrayDD(1 To rcnt, 1 To 7)
ReDim ArrayRetail(1 To rcnt, 1 To 7)

'Group by Respective Bank Accts
For i = LBound(rCol, 1) To UBound(rCol, 1)

    If Len(rCol(i, 2)) <> 10 Then
        MsgBox "The Description for Cell: B" & i + 3 & " [Column B Row " & i + 3 & "] must include a 10 digit Acct Number"
        Exit Sub
    Else
    End If

    For j = LBound(rCol, 2) To UBound(rCol, 2)
        Select Case rCol(i, 2)
            Case MFGWholesale
                ArrayMFG(i, j) = rCol(i, 7) + ArrayMFG(i, 7)
            Case DealerDirect
                ArrayDD(i, j) = rCol(i, 7) + ArrayDD(i, 7)
            Case Retail
                ArrayRetail(i, j) = rCol(i, 7) + ArrayRetail(i, 7)
        End Select
    Next j
Next i

Dest.Value = Application.WorksheetFunction.Sum(ArrayMFG) 
Debug.Print Dest.Value
Dest.Value = Application.WorksheetFunction.Sum(ArrayDD)
Debug.Print Dest.Value
Dest.Value = Application.WorksheetFunction.Sum(ArrayRetail)
Debug.Print Dest.Value

With Application
.ScreenUpdating = True
.Calculation = xlCalculationAutomatic
End With

End Sub
答案

我通过修补找到了答案。数组(i,2)其中2表示Range中的第二列,这是我想要的。对于任何考虑答案的人来说

For j = LBound(rCol, 2) To UBound(rCol, 2)
    Select Case rCol(i, 2)
        Case MFGWholesale
            ArrayMFG(i, 2) = rCol(i, 7) + ArrayMFG(i, 7)
        Case DealerDirect
            ArrayDD(i, 2) = rCol(i, 7) + ArrayDD(i, 7)
        Case Retail
            ArrayRetail(i, 2) = rCol(i, 7) + ArrayRetail(i, 7)
    End Select
Next j

以上是关于填充2维VBA阵列Excel的主要内容,如果未能解决你的问题,请参考以下文章

Excel VBA 自动填充目标

VBA Excel 2010 - 自动填充不填充

Excel VBA 跨列自动填充

Excel VBA:自动填充动态范围错误

如何使用 VBA 根据活动工作表中的单元格自动填充 Excel 表单?

VBA Excel - 自动填充方法超出范围类错误