大家好,所以我对 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
最佳答案
下面的代码
D6
到 D
列中最后使用的单元格strV
将该范围内的所有值连接到一个字符串 ( Join
) [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)代码
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/