我正在寻找一种方法来计算相同物品代码(数量)的不同时间段的总和和标准差。它与excel中的Subtotal函数非常相似,但是,不是对数字进行分组,而是创建一个新行并在同一列中插入小计 - 我想使用VBA自动执行此函数并将小计放在相邻的列或表中。我已经为小计记录了一个宏,但是,我需要下一列中的stdDev而不进行分组,或者打破电子表格上的数据。我需要这些数据用于其他代码。
任何建议都将不胜感激。感谢
Sub stdDeviation(RN)
Dim FirstOccurrence As Long
Dim LastOccurrence As Long
Dim i As Integer
RN2 = RN
C = Sheets("CONETRAN").Cells(RN2, 2)
Do Until Sheets("CONETRAN").Cells(RN2, 2) <> C
RN2 = RN2 + 1
Loop
RN2 = RN2 - 1
FirstOccurrence = RN
LastOccurrence = RN2
For i = 1 To LastOccurrence
Sheets("conedetail").Cells(RN, 16).Value = Application.WorksheetFunction.StDev(Range("J" & FirstOccurrence & ":J" & LastOccurrence))
Next
End Sub
答案 0 :(得分:2)
假设您在行B中有一个固定的数据块来自$B$1:$B44931
,并且假设列B中的所有值都已经排序,您可以使用以下方法实现您想要的内容:
查找第一次出现的项目代码(编号)的行号
Dim FirstOccurrence As Long
FirstOccurrence = Range("B:B").Find(What:="47-901-049W2", After:=[B1], SearchDirection:=xlNext).Row
查找最后一次出现的项目代码(编号)的行号
Dim LastOccurrence As Long
LastOccurrence = Range("B:B").Find(What:="47-901-049W2", After:=[B1], SearchDirection:=xlPrevious).Row
对使用前两个点指定的范围执行StDev操作并写入您喜欢的任何单元格
Cells(1, 17).Value = Application.WorksheetFunction.StDev(Range("J" & FirstOccurrence & ":J" & LastOccurrence))
您可能需要将此全部嵌套在一个循环中,以便您在最后计算的StDev下面继续写入,以便循环显示所有项目代码。
为了让您的生活更轻松,我建议添加一个新列,复制B列中的所有值。选择所有新复制的单元格,单击数据选项卡 - &gt;删除重复项。现在,在For Loop
中使用此范围的单元格来运行搜索。
<强>更新强>
好的,所以你的代码是一个很好的尝试,但它有一些问题。两个主要的事情是:
您需要创建一个处理第一个数据点的条件处理程序(If Statement
)。因为你是从&#34; B1&#34;第一个FirstOccurrence
需要是B2-1 = B1
您需要创建一个条件处理程序(If Statement
)来处理只有一个数据点的实例(即,当起点和终点都引用同一行时。
尝试使用此代码:
Sub stdDeviation()
Dim FirstOccurrence As Long
Dim LastOccurence As Long
Dim RN As Range
Dim workingRange As Range
Dim UniqueRange As Range
Dim i As Long
Set workingRange = Sheets("conedetail").Range("B1:B49999")
Set UniqueRange = Sheets("conedetail").Range("G1:G5") 'Insert the location of the extra column you created with all unique item codes
i = 1 'This sets up your writing position
'This loops throug all the unique item numbers and retrieves and calculates the necessary data
For Each RN In UniqueRange
'Need to place a control factor in for the very first set of data
If RN.Row = 1 Then
FirstOccurrence = workingRange.Find(What:=RN.Text, After:=[B1], SearchDirection:=xlNext).Row - 1
Else
FirstOccurrence = workingRange.Find(What:=RN.Text, After:=[B1], SearchDirection:=xlNext).Row
End If
LastOccurence = workingRange.Find(What:=RN.Text, After:=[B1], SearchDirection:=xlPrevious).Row
'Tests to see if only one occurrence, if no calculates stDev normally
If LastOccurence - FirstOccurrence = 0 Then
'Insert whatever you want it to do here if there is only one data point
Sheets("conedetail").Cells(i, 16).Value = 0
Else
Sheets("conedetail").Cells(i, 16).Value = Application.WorksheetFunction.StDev(Range("J" & FirstOccurrence & ":J" & LastOccurence))
End If
i = i + 1
Next RN
Set RN = Nothing
Set workingRange = Nothing
Set UniqueRange = Nothing
End Sub