写一个VBA代码实现以下需求1.创建字典,确认表1的F列字符串及个数,2.将字典的字符串返回表2的A列,对应个数返回给B列,3.将字典的字符串有几个就粘贴几个到表3A列
时间: 2024-03-02 18:53:46 浏览: 49
以下是实现上述需求的VBA代码:
```
Sub Dictionary()
'创建字典对象
Dim dict As Object
Set dict = CreateObject("Scripting.Dictionary")
'获取表1中F列的字符串及个数
Dim lastRow As Long
lastRow = Worksheets("表1").Cells(Rows.Count, "F").End(xlUp).Row
Dim str As String
Dim count As Long
For i = 2 To lastRow
str = Worksheets("表1").Range("F" & i).Value
If dict.Exists(str) Then
count = dict(str) + 1
dict(str) = count
Else
dict.Add str, 1
End If
Next i
'将字典的字符串返回表2的A列,对应个数返回给B列
Dim j As Long
j = 2
For Each key In dict
Worksheets("表2").Range("A" & j).Value = key
Worksheets("表2").Range("B" & j).Value = dict(key)
j = j + 1
Next key
'将字典的字符串有几个就粘贴几个到表3A列
j = 2
For Each key In dict
For k = 1 To dict(key)
Worksheets("表3").Range("A" & j).Value = key
j = j + 1
Next k
Next key
End Sub
```
注意:在使用该代码时,需要将代码中的“表1”、“表2”、“表3”修改成实际的工作表名称。
阅读全文