我正在尝试创建一些VB代码以在Excel中创建宏。然而,我之前只使用过Python和Java,所以这个全新的问题是,我有一个单元格,其中包含一个由逗号分隔并存储为字符串的数字列表,例如12,5,7,9。这已从其他地方进行了计算。我希望能够遍历数字列表,将它们拆分,将它们转换为整数,然后根据它们的数量来计算它们的平均值。我希望这适用于当前选定的单元格并在下一个单元格中显示结果。
这是我到目前为止所做的代码。它不起作用,我不能测试它,因为我运行它时需要获取所需的错误对象。任何建议都会很棒。感谢。
Sub CalculateAverage()
Dim contents As String
Dim cell As Range
Dim NumbersArray() As String
Set cell = ActiveCell.Select()
contents = Range(cell).value
NumbersArray = Split(contents, ",")
Dim count As Integer
Dim lengthOfArray As Integer
Dim first As Integer
Dim last As Integer
first = LBound(NumbersArray)
last = UBound(NumbersArray)
lengthOfArray = last - first
Dim total As Integer
Dim value As Integer
count = 0
While count <= lengthOfArray
total = total + CInt(NumbersArray(count))
count = count + 1
Wend
Dim average As Double
average = total / count
Range("A2").value = average
End Sub
答案 0 :(得分:2)
我会用用户定义的函数来解决这个问题。类似的东西:
Function CalculateAverage(s As String) As Double
Dim v As Variant, i As Long, total As Double
v = Split(s, ",")
For i = 0 To UBound(v) 'LBound(v) = 0
total = total + v(i) 'VBA will coerce the values to double
Next i
CalculateAverage = total / (UBound(v) + 1)
End Function
它的工作原理如下:
您可以直接在电子表格中使用此功能,但也可以从子系统中调用它。
对您的代码提出几点意见:
1)使用Long
代替Integer
。整数可能太容易溢出
2除非你有充分的理由使用整数,否则在电子表格值中使用双精度更为惯用。
答案 1 :(得分:1)
仅举例说明如何使用Evaluate
Sub test()
Debug.Print Evaluate("=Average(" & [A1].Value2 & ")")
End Sub
测试
答案 2 :(得分:0)
尝试将Set cell = ActiveCell.Select()
更改为Set cell = Selection
和contents = Range(cell).value
更改为contents = cell.value
或者只需删除Set cell = ActiveCell.Select()
行,然后将contents = Range(cell).value
更改为contents = Selection.value
注意:当选择单个单元格时,这将起作用
下面的代码将在&#34; B&#34;列中输入平均值。对于选择的单个或多个单元格 - 仅限单列选择:
Sub CalculateAverage()
Dim contents As String
Dim cell As Range
Dim NumbersArray() As String
Dim c As Range
Set cell = Selection
For Each c In cell
contents = c.value
NumbersArray = Split(contents, ",")
Dim count As Integer
Dim lengthOfArray As Integer
Dim first As Integer
Dim last As Integer
first = LBound(NumbersArray)
last = UBound(NumbersArray)
lengthOfArray = last - first
Dim total As Integer
Dim value As Integer
total = 0
value = 0
count = 0
While count <= lengthOfArray
total = total + CInt(NumbersArray(count))
count = count + 1
Wend
Dim average As Double
average = 0
average = total / count
'Assuming your data is in column "A" average will be entered in column "B"
Cells(c.Row, "B").value = average
Next c
End Sub