Countif仅返回1

时间:2019-04-29 20:04:52

标签: excel vba

VBA的新增功能,并试图编写一个语句,该语句计算一列中出现“男性”一词的次数。我正在使用此代码:

def entropy(attributes, dataset, targetAttr):
    freq = {}
    entropy = 0.0
    index = 0
    for item in attributes:
        if (targetAttr == item):
            break
        else:
            index = index + 1
    index = index - 1
    for item in dataset:
        if ((item[index]) in freq):
            # Increase the index
            freq[item[index]] += 1.0
        else:
            # Initialize it by setting it to 0
            freq[item[index]] = 1.0

    for freq in freq.values():
        entropy = entropy + (-freq / len(dataset)) * math.log(freq / len(dataset), 2)
    return entropy

消息框显示1,在该列中有四个单词Male的实例。

谢谢!

1 个答案:

答案 0 :(得分:1)

您以错误的方式使用worksheet函数,该函数为您返回countif,只是将其放入变量中。

       ForeignCount   = 0
       ForeignCount  = WorksheetFunction.countif(Worksheets("Sheet1").Range("D2:D10"), "Male") 
       MsgBox ForeignCount
相关问题