excel - 在VBA中找到字符出现在单元格范围内的单个单元格中的最大次数

标签 excel vba

在开始之前,我只想提前感谢每一位贡献者。我之前只发布了一个问题,我惊讶于我得到回复的速度以及在研究解决方案后我学到了多少。我希望我很快就会有足够的声望点来开始支持我在这里找到的好的解决方案。
无论如何,我要做的是返回一个数字,该数字是出现在工作表列的单个单元格中的最大名称数。该列中的每个单元格都可以包含任意数量的名称。每个名称都由管道“|”分隔,因此我计算管道数,然后添加一个以获取每个单元格中名称的数量。例如:单元格值为“Bob | Jon | Larry” = 2pipes +1 = 3 个名字。
我下面的代码有效,但我需要对数万条记录执行此操作。我不认为我的解决方案是一种好的或有效的方法(如果我错了,请告诉我)。所以我的问题是:

  • 有没有更好的方法来实现这一点,例如不遍历范围内的每个单元格?
  • 如果没有完全不同的方法,我怎样才能避免在新列的单元格中实际打印名称计数?我可以将这些值存储在一个数组中并计算数组的最大值吗? (也许您可以指出这个主题已经有一个线程?)
  • Sub charCnt()
    
    Application.ScreenUpdating = True
    Application.Calculation = xlCalculationManual
    
    Dim wb As Workbook: Set wb = ThisWorkbook
    Dim ws As Worksheet: Set ws = Worksheets("Leasing")
    Dim vRange As Variant
    Dim iCharCnt As Integer
    Dim iRows As Integer
    Dim i As Integer
    Dim iMax As Integer
    
    Const sFindChar As String = "|"
    
    iRows = ws.Cells(Rows.Count, "A").End(xlUp).Row 'count number of rows
    
    For i = 1 To iRows
         vRange = Cells(i, "O") 'column O has the names
        iCharCnt = Len(vRange) - Len(Replace(vRange, sFindChar, "")) 'find number of | in single cell.
        ws.Cells(i, "W") = iCharCnt 'column W is an empty column I use to store the name counts
    Next i
    
    iMax = Application.WorksheetFunction.Max(Range("W:W")) + 1 'return max from column W
        
    Application.ScreenUpdating = True
    Application.Calculation = xlCalculationAutomatic
    MsgBox ("Max number of names in one cell is " & iMax) ' show result
    
    End Sub
    

    最佳答案

    最大子串数

    Option Explicit
    
    Sub charCount()
    
        Const cCol As String = "O"
        Const fRow As Long = 1
        Const Delimiter As String = "|"
        
        Dim wb As Workbook: Set wb = ThisWorkbook
        Dim ws As Worksheet: Set ws = wb.Worksheets("Leasing")
        Dim lRow As Long: lRow = ws.Cells(ws.Rows.Count, cCol).End(xlUp).Row
        Dim rg As Range: Set rg = ws.Cells(fRow, cCol).Resize(lRow - fRow + 1)
        Dim Data As Variant: Data = rg.Value
        
        Dim i As Long
        For i = 1 To UBound(Data, 1)
            Data(i, 1) = Len(Data(i, 1)) - Len(Replace(Data(i, 1), Delimiter, ""))
        Next i
        Dim iMax As Long: iMax = Application.Max(Data) + 1
        
        MsgBox ("Max number of names in one cell is " & iMax) ' show result
    
    End Sub
    

    关于excel - 在VBA中找到字符出现在单元格范围内的单个单元格中的最大次数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66716321/

    相关文章:

    vba - Excel 页眉/页脚不会通过 VBA 更改,除非为空

    vba - 如何锁定包含公式的单元格但仍允许宏工作?

    vba - 对于开始到结束循环,结束变量更改中间循环

    excel - VBA使用公式将行插入到特定表格的底部

    c# - 动态解析 Excel 工作表(未提供单元格范围,因为数据在工作表中的位置可能会动态变化)

    excel - VBA粘贴不遵循If语句

    vba - 如何以编程方式使用 Excel 图表中的每个第 n 个单元格

    python - xlwings for Excel for Mac 2016

    excel - 从工作表上的单元格获取值

    excel - 如果其他两个单元格匹配,则选择一个单元格的宏