Excel 根据年份和唯一代码对多个数组的值进行排序
我有一个包含大量数据的excel文档。我使用了四列Excel 根据年份和唯一代码对多个数组的值进行排序,excel,vba,Excel,Vba,我有一个包含大量数据的excel文档。我使用了四列 会计年度 无效对冲的收益/损失 SIC代码 对唯一的SIC代码进行排序,这样就不会有人出现多次 我已经创建了4个数组并在其中存储了值 我想做的,但现在有一些问题,是每年(从2001年到2018年)计算每个SIC代码每年的平均收益/损失(2)。我编写了以下代码: Sub-Assignment4() 将Wb设置为工作簿 将Ws设置为工作表 设置Wb=ThisWorkbook 设置Ws=ThisWorkbook.Worksheets(“Sheet1
Sub-Assignment4()
将Wb设置为工作簿
将Ws设置为工作表
设置Wb=ThisWorkbook
设置Ws=ThisWorkbook.Worksheets(“Sheet1”)
Dim iLastRow为整数,iLastRow2为整数
Dim readStart为整数
将计数设置为整数
Dim ArrayFiscalYear()作为字符串
Dim ArrayGL()作为字符串
Dim ArraySIC()作为变量
Dim ArraySICSorted()为整数
雷迪姆阵列财年(10000)
雷迪姆阵列(10000)
雷迪姆阵列物理(10000)
ReDim阵列排序(10000)
将年份设置为整数
Dim arr作为新系列,a
Dim j尽可能长
暗x等长
双精度平均值
双份点心
作为整数的Dim计数器
iLastRow=Ws.Cells(Rows.count,“J”).End(xlUp).Row
计数=2
readStart=2
Do While(count)您是否尝试过使用透视表?或者您是否有理由需要使用VBA创建此摘要?我更喜欢vbaIn Excel O365,您可以使用工作表公式进行此操作。使用Power Query(或者简单透视表)也很简单。如果您必须使用VBA,我会创建一个字典字典,从中我认为可以更容易地计算您想要的结果。到底出了什么问题?您得到了什么结果?与您预期的结果相比?
Sub Assignment4()
Dim Wb As Workbook
Dim Ws As Worksheet
Set Wb = ThisWorkbook
Set Ws = ThisWorkbook.Worksheets("Sheet1")
Dim iLastRow As Integer, iLastRow2 As Integer
Dim readStart As Integer
Dim count As Integer
Dim ArrayFiscalYear() As String
Dim ArrayGL() As String
Dim ArraySIC() As Variant
Dim ArraySICSorted() As Integer
ReDim ArrayFiscalYear(10000)
ReDim ArrayGL(10000)
ReDim ArraySIC(10000)
ReDim ArraySICSorted(10000)
Dim year As Integer
Dim arr As New Collection, a
Dim j As Long
Dim x As Long
Dim avg As Double
Dim sum As Double
Dim counter As Integer
iLastRow = Ws.Cells(Rows.count, "J").End(xlUp).Row
count = 2
readStart = 2
Do While (count <= iLastRow)
ArraySIC(count) = Ws.Cells(count, 10)
count = count + 1
Loop
Ws.Range("J2:J" & iLastRow).AdvancedFilter _
Action:=xlFilterCopy, _
CopyToRange:=Ws.Range("L1"), _
Unique:=True
Ws.Cells(1, 12) = "Sorted SIC"
iLastRow2 = Ws.Cells(Rows.count, "L").End(xlUp).Row
Debug.Print (iLastRow2)
count = 0
counter = 2
Do While (count <= iLastRow2)
ArraySICSorted(count) = Ws.Cells(counter, 12)
Debug.Print (ArraySICSorted(count))
count = count + 1
counter = counter + 1
Loop
Ws.Columns(12).EntireColumn.Delete
i = 2
year = 2001
count = 0
x = 1
Do While year <= 2018
For x = LBound(ArraySICSorted) To UBound(ArraySICSorted)
For i = 1 To iLastRow
If Ws.Cells(i, 3) = year Then
ArrayFiscalYear(year) = Ws.Cells(i, 3)
ArrayGL(year) = Ws.Cells(i, 8)
ArraySIC(year) = Ws.Cells(i, 10)
count = count + 1
sum = sum + ArrayGL(year)
End If
Next i
avg = sum / count
Debug.Print (count & " --- " & ArraySICSorted(x) & " --- " & year & " --- " & x)
sum = 0
count = 0
If x >= 62 Then
year = year + 1
Exit For
End If
Next x
Loop
End Sub