excel中的for循环(等同于bash)

时间:2014-08-07 14:17:26

标签: excel excel-vba excel-formula vba

我正在使用excel中的大型数据库。我必须计算特定细胞的平均分数。然而,单元格中的数值(以及由单元格表示A4,D5等)不对应于计算分数时需要添加的值。到目前为止,我一直在使用这样的东西:

=(sum(if(A1=1,3,IF(A1=2,2,IF(A1=3,1,IF(A1=4,0,"NA")))))+
+IF(F1=1,2,IF((F=2,2,IF(F=3,1,IF(F=4,0,"NA")))))+IF(....

等等。如果包含1的单元格占总得分的3,则包含2 - 2的单元格,包含3到1的单元格等。

但是,我确信应该有一种更快更清洁的计算方法。有没有一种方法可以在excel中使用与下面类似的结构?

for A1,AB1,AC1...[the desired cells); do; 
 if $column=1,3
 if $column=3,1
 if $column=4,0 ; done

先谢谢你的帮助!

最佳, [R

2 个答案:

答案 0 :(得分:0)

您需要在尝试迭代的单元格上进行For ... Next循环,并根据值分配“分数”的条件逻辑。对于像您所拥有的非连续单元格而言,循环有点棘手。

我会创建一个分隔的字符串,然后使用Split函数将其转换为一个数组,您可以通过该数组进行迭代,分配给Range对象来表示迭代中的每个单元格。 / p>

Dim cellsList as String
Dim cells as Variant
Dim c as Variant
Dim cl as Range
Dim score as Integer
Dim totalScore as Integer
Dim naCount as Integer
cellsList = "A1,AB1,AC1" 'Modify as needed

'convert delimited string to an array:
cells = Split(cellsList, ",")
For each c in cells
    Set cl = Range(c)
    Select Case cl.Value
        Case 1
            score = 3
        Case 2
            naCount = naCount + 1 'keep track of these since they will not be included in the mean score
        Case 3
            score = 1
        Case 4
            score = 0
    End Select

    totalScore = totalScore + score
Next
'Display the average score:
MsgBox totalScore / ((UBound(cells) + 1) - naCount)

答案 1 :(得分:0)

得分就像 4值那么如果你只想使用EXCEL:
为要添加的选定单元格创建名称(不必附近...)。 (样本xx)。
在单元格中插入公式:

=4*COUNT(xx)-SUM(xx)