帮我写一段vba代码:统计A列和D列中相同字符数,把数量列在H列,相同字符列在I列,接着,用H列数据除以统计A列字符数量列在J列
时间: 2024-05-06 15:17:58 浏览: 136
VBA示例之 在Excel中对多列进行填充
以下是实现您要求的 VBA 代码:
```
Sub countCharacters()
Dim lastRow As Long
Dim i As Long, j As Long, k As Long
Dim count As Long
Dim dict As Object
Set dict = CreateObject("Scripting.Dictionary")
lastRow = Cells(Rows.count, "A").End(xlUp).Row
' 统计A列和D列中相同字符数
For i = 1 To lastRow
If Not dict.Exists(Cells(i, "A").Value) Then
count = 1
For j = i + 1 To lastRow
If Cells(j, "A").Value = Cells(i, "A").Value And Cells(j, "D").Value = Cells(i, "D").Value Then
count = count + 1
End If
Next j
dict.Add Cells(i, "A").Value & Cells(i, "D").Value, count
End If
Next i
' 把数量列在H列,相同字符列在I列
k = 1
For Each key In dict.Keys
Cells(k, "H").Value = dict(key)
Cells(k, "I").Value = key
k = k + 1
Next key
' 用H列数据除以统计A列字符数量列在J列
For i = 1 To lastRow
Cells(i, "J").Value = dict(Cells(i, "A").Value & Cells(i, "D").Value) / Len(Cells(i, "A").Value)
Next i
End Sub
```
这段代码首先创建了一个字典对象 `dict`,用于存储统计结果。接着,使用两个循环分别统计 A 列和 D 列中相同字符的数量,并将结果保存到 `dict` 中。最后,再次循环 A 列,将数量和相同字符信息分别保存到 H 列和 I 列,并且计算出数量除以统计 A 列字符数量的结果保存到 J 列。
阅读全文