Excel中的重复单词

时间:2017-08-25 07:24:40

标签: excel

我如何算作" 2"如果这个词" apple"显示在row3和row4的同一行?我需要的代码是在Microsoft excel 2010而不是vba

预期产出:

enter image description here

2 个答案:

答案 0 :(得分:0)

非常接近找出一个公式,但我害怕在受到厌倦之后我保留并创建了一个UDF。

将以下内容粘贴到vba编辑器中的模块中(现在也必须将文件另存为.xlsm)。这适用于所有2D范围(即行数和列数都大于1),您可以使用{1}}的1D范围,如上面的评论中所述。

COUNTIF

并使用Public Function CountStringOccurence(count_text As String, within_range As Range) As Long Dim arr As Variant Dim i As Long ' Create array of 1's and 0's (Numerical trues and falses) arr = Application.Evaluate("--(" & within_range.Parent.Name & "!" & within_range.Address & "=""" & count_text & """)") ' Loop through each row array For i = LBound(arr, 1) To UBound(arr, 1) ' Get max value in each row and sum (i.e. if there is a True present add it to the total count) CountStringOccurence = CountStringOccurence + Application.Max(Application.Index(arr, i, 0)) Next i End Function

进行调用

在函数中,如果范围中的值与想要的字符串匹配,则首先从范围填充数组1,如果不是,则填充0。然后循环遍历数组中的每一行,将行中的最大值相加(即如果值存在则为1,如果不存在则为0)。然后它将答案反馈给Excel单元格

如果有人可以想出一个公式,虽然我很乐意看到它。

如果您可以向工作表添加额外的列,您还可以实现此目的: 工作表中的最后一列为每行输入CountStringOccurence(B7,A3:G4),然后对此列求和以获得答案

答案 1 :(得分:0)

这可能不是最简单的方法,但是你去了:

Public Sub getRowCountOfStringOccurance()

    Dim thisRange As Range
    Set thisRange = Selection

    MsgBox (countStringOccurancesInRows("apple", thisRange))


End Sub
Public Function countStringOccurancesInRows(stringToFind As String, searchRange As Range) As Integer

    Dim wb As Workbook
    Set wb = ActiveWorkbook

    Dim ws As Worksheet
    Set ws = wb.ActiveSheet

    Dim firstRow As Integer
    Dim lastRow As Integer

    Dim firstColumn As Integer
    Dim lastColumn As Integer

    Dim rowOccurances As Integer
    rowOccurances = 0

    Dim occurances As Integer
    occurances = 0

    firstRow = searchRange.Rows(1).Row
    lastRow = searchRange.Rows.Count + firstRow - 1

    firstColumn = searchRange.Columns(1).Column
    lastColumn = searchRange.Columns.Count + firstColumn - 1

    For thisRow = firstRow To lastRow
        For thisColumn = firstColumn To lastColumn
            If (ws.Cells(thisRow, thisColumn) = stringToFind) Then
                rowOccurances = rowOccurances + 1
            End If
        Next
        If (rowOccurances > 0) Then
            occurances = occurances + 1
        End If
    Next

    countStringOccurancesInRows = occurances

End Function

请注意我暂时输入了字符串,并且必须在工作表中选择要搜索的范围。然后它会给出一个带有结果的消息框。在测试时我没有任何问题。