继续VBA,本次为数据统计相关自定义函数!
本帖最后由 sleony 于 2024-1-17 11:13 编辑1.函数功能,单元格数据中(可能一个单元格中有多个数据以各种分割符分割),对数据进行清洗后进行指定运算
(极差/平均值/标准偏差(基于目前样本预估整体)/等等)
Function CustomRangeVariance(rngArray As Range, splitCters As String, funcitonAlg As Integer, resDigits As Integer) As Double
Rem rngArray是需要计算的连续单元格区域,比如:a1:b10
Rem splitCters是指定的分割字符,比如"\"
Rem functionAlg 是指定的计算模式,0是求极差,1是计算算术平均值,2是计算标准偏差
Rem resDigits是指定保留最后计算数据的位数,2是保留2位小数
' 声明变量
Dim allValues() As String
Dim dblValues() As Double
Dim iArea As Long, iCell As Long, iValue As Long
Dim maxValue As Double, minValue As Double
Dim CELL As Range, I, rng As Range
ReDim dblValues(1 To 1000) ' 初始化足够大的数组,根据实际情况调整大小
iValue = 1
For Each CELL In rngArray.Cells
' 获取单元格内的文本值并分割成数组
Dim strValues As String
strValues = CELL.Value
Dim arrValues() As String
arrValues = Split(strValues, splitCters)
For I = LBound(arrValues) To UBound(arrValues)
If IsNumeric(arrValues(I)) Then
dblValues(iValue) = CDbl(arrValues(I))
iValue = iValue + 1
End If
Next I
Next CELL
ReDim Preserve dblValues(1 To iValue - 1)
If funcitonAlg = 0 Then
If UBound(dblValues) > 0 Then
maxValue = Application.WorksheetFunction.Max(dblValues)
minValue = Application.WorksheetFunction.Min(dblValues)
CustomRangeVariance = Format(Round(maxValue - minValue, resDigits), "#.00")
Else
CustomRangeVariance = "无有效数据"
End If
ElseIf funcitonAlg = 1 Then
Rem Format(roundedValue, "#.00")
CustomRangeVariance = Format(Round(Application.WorksheetFunction.Average(dblValues), resDigits), "#.00")
Else
CustomRangeVariance = Format(Round(Application.WorksheetFunction.StDevP(dblValues), resDigits), "#.00")
End If
End Function
2.函数功能,单元格数据中(可能一个单元格中有多个数据或者以各种分割符分割),对数据/字符进行清洗后进行指定字符进行计数,(可以利用内置函数进行二次开发更多其他功能)
Function SpeSymbolcount(rngArray As Range, splitCters As String, countCha As String)
Rem 三个参数,数据单元格区域,分割字符,指定计数的字符
Rem rngArray是需要计算的连续单元格区域,比如:a1:b10
Rem splitCters是指定的分割字符,比如"\"
Rem countCha是指定的需要被计数的字符,比如"+"
Dim dblValues() As Double
Dim CELL As Range, I, rng As Range
Dim iValue As Long
ReDim dblValues(1 To 1000) ' 初始化足够大的数组,根据实际情况调整大小
iValue = 0
For Each CELL In rngArray.Cells
' 获取单元格内的文本值并分割成数组
Dim strValues As String
strValues = CELL.Value
Dim arrValues() As String
arrValues = Split(strValues, splitCters) ' 将分割出的字符串转换为数值并存储到dblValues数组中
For I = LBound(arrValues) To UBound(arrValues)
If arrValues(I) = countCha Then
iValue = iValue + 1
End If
Next I
Next CELL
SpeSymbolcount = iValue
End Function
学习下,Excel应该有函数实现吧~ gavinfeng 发表于 2024-1-16 17:47
学习下,Excel应该有函数实现吧~
这个是个人做的自定义函数,暂时没发现有内置函数相同的
或者用多个内置函数嵌套,太麻烦了
直接写一个自定义函数算了
页:
[1]