vba - 在VBA中计算数组中某些字符的数量

标签 vba excel

大家好,所以我对 VBA 很陌生,但是上过一些 Java 和 HTML 的初学者类(class),所以我几乎知道我在做什么。

所以我有一个单元格,我想根据逗号 (,) 在其中拆分
我想计算某个字符的出现次数,然后在另一个单元格中显示该结果。在该单列中沿着这些行的一列向下执行此操作。

例如:y,y,y,n,y = 在单元格 D6 中:4

下面是我用我在网上学到的关于 VBA 的一点点信息生成的代码。

I have also seen this bit of code but it get very complex very fast (link) so if someone could explain that one instead I would be very grateful.

(我试图评论答案,但没有足够的代表这样做)

并且请在给出答案时尝试解释这些方法,我不了解每种方法的作用,对编程和 VBA 都是新手,所以在回复您的回复时,看看我是否能够通过一点插入来弄清楚.

    Private Sub CommandButton15_Click()

Dim Number As String
Dim Yoccur As Integer
Dim Noccur As Integer
Dim Notapp As Integer


Dim length As Integer
Dim current As String


Dim i As Integer


Dim Row As Integer

Do While Row < 84
For i = 1 To length


'parse data into a array here

'tempArr = Split(X(lngRow, 2), ",")
' would that work if I tried to split based on the comma?


If current = "y" Then Yoccur = Yoccur + 1
If current = "n" Then Noccur = Noccur + 1
If current = "n/a" Then Notapp = Notapp + 1

Next i

Wend


Range("d45").Value = Yoccur
Range("d46").Value = Noccur
Range("d47").Value = Notapp


End Sub

最佳答案

下面的代码

  • 设置范围为 D6D 列中最后使用的单元格
  • 它使用 strV 将该范围内的所有值连接到一个字符串 ( Join )
  • 它通过从未更改字符串的长度中减去所有 y 字符的字符串长度来转储 A1 中 y 值的数量(下面有更详细的说明)
  • [a1] = Len(strV) - Len(Replace(strV, "y", vbNullString))将 y 值的数量放入 A1
  • [a3] = (Len(strV) - Len(Replace(strV, "n/a", vbNullString))) / 3将 n/a 值的数量放入 A2 (需要 /3 来计算删除 3 个字符长度 n/a 作为一个替换)
  • [a2].Value = Len(strV) - Len(Replace(strV, "n", vbNullString)) - [a3].Value]计算 n 个值的数量 - A3 中 n/a 值的数量(因为 n/a 包含 n)

  • enter image description here

    代码
    Sub QuickDump()
    Dim rng1 As Range
    Dim strV As String
    Set rng1 = Range([d6], Cells(Rows.Count, "d").End(xlUp))
    strV = Join(Application.Transpose(rng1.Value), ",")
    d = Filter(Application.Transpose(rng1.Value), "y", True, vbTextCompare)
    [a1] = Len(strV) - Len(Replace(strV, "y", vbNullString))
    [a3] = (Len(strV) - Len(Replace(strV, "n/a", vbNullString))) / 3
    [a2].Value = Len(strV) - Len(Replace(strV, "n", vbNullString)) - [a3].Value
    End Sub
    

    关于vba - 在VBA中计算数组中某些字符的数量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24836219/

    相关文章:

    java - 结果集 -> XLS

    vba - 创建新工作表,然后返回到上一个事件工作表

    vba - 如何将 VBA Debug.Print 输出记录到文本文件?

    excel - 读取特定字符串的文本文件,如果未找到则打开 msgbox

    从 Access 通过电子邮件发送 PDF

    excel - 循环文件夹并删除 .xlsm 文件

    Excel VBA 突出显示事件列中的重复项

    Excel公式查找范围内字母 "x"的出现

    vba - 在vba中使用10或很多小数格式化为百分比

    excel - VBA 中的选择命令更改为小写