【发布时间】:2015-06-02 06:30:32
【问题描述】:
我正在尝试在 Excel 中编写一个宏来计算 A 列中相同文本的标准偏差,从 B 列中获取值并在 C 列中给出结果:
我通过将 equation=STDEV.S(A2;A3;A4;A16)for "aaa" 手动完成。但我需要自动执行此操作,因为我正在执行另一个由宏完成的计算和程序。这是我的代码:
Option Explicit
Sub Main()
CollectArray "A", "D"
DoSum "D", "E", "A", "B"
End Sub
' collect array from a specific column and print it to a new one without duplicates
' params:
' fromColumn - this is the column you need to remove duplicates from
' toColumn - this will reprint the array without the duplicates
Sub CollectArray(fromColumn As String, toColumn As String)
ReDim arr(0) As String
Dim i As Long
For i = 1 To Range(fromColumn & Rows.Count).End(xlUp).Row
arr(UBound(arr)) = Range(fromColumn & i)
ReDim Preserve arr(UBound(arr) + 1)
Next i
ReDim Preserve arr(UBound(arr) - 1)
RemoveDuplicate arr
Range(toColumn & "1:" & toColumn & Range(toColumn & Rows.Count).End(xlUp).Row).ClearContents
For i = LBound(arr) To UBound(arr)
Range(toColumn & i + 1) = arr(i)
Next i
End Sub
' sums up values from one column against the other column
' params:
' fromColumn - this is the column with string to match against
' toColumn - this is where the SUM will be printed to
' originalColumn - this is the original column including duplicate
' valueColumn - this is the column with the values to sum
Private Sub DoSum(fromColumn As String, toColumn As String, originalColumn As String, valueColumn As String)
Range(toColumn & "1:" & toColumn & Range(toColumn & Rows.Count).End(xlUp).Row).ClearContents
Dim i As Long
For i = 1 To Range(fromColumn & Rows.Count).End(xlUp).Row
Range(toColumn & i) = WorksheetFunction.SumIf(Range(originalColumn & ":" & originalColumn), Range(fromColumn & i), Range(valueColumn & ":" & valueColumn))
Next i
End Sub
Private Sub RemoveDuplicate(ByRef StringArray() As String)
Dim lowBound$, UpBound&, A&, B&, cur&, tempArray() As String
If (Not StringArray) = True Then Exit Sub
lowBound = LBound(StringArray): UpBound = UBound(StringArray)
ReDim tempArray(lowBound To UpBound)
cur = lowBound: tempArray(cur) = StringArray(lowBound)
For A = lowBound + 1 To UpBound
For B = lowBound To cur
If LenB(tempArray(B)) = LenB(StringArray(A)) Then
If InStrB(1, StringArray(A), tempArray(B), vbBinaryCompare) = 1 Then Exit For
End If
Next B
If B > cur Then cur = B
tempArray(cur) = StringArray(A)
Next A
ReDim Preserve tempArray(lowBound To cur): StringArray = tempArray
End Sub
如果有人能给我一个想法或解决方案,那就太好了。上面的代码用于计算相同文本值的总和。有没有办法修改我的代码来计算标准偏差?
【问题讨论】:
-
亲爱的,请您再检查一下我的问题。因为不久前我用一个代码更新了我的问题。 @pnuts
-
a) 你是说
=STDEV.S(B2; B3; B4; B16)代表“aaa”吗? b) C 列的公式是否有效还是必须是宏? -
bbb、ccc 和 www 看起来只有三个值,而不是其他四个?
-
如果宏对于解决方案不是必需的,那么创建数据透视表并使用基于数据透视表的 INDEX MATCH 公式填充 c 列怎么样?
-
@pnuts,我会认为我的手腕被打了:-)
标签: vba excel standard-deviation