请使用VBA代码
时间: 2024-02-09 10:12:52 浏览: 66
好的,以下是使用VBA代码实现在sheet2中创建一个名为“count”的新列,并统计sheet1中“hospitalID”每个值的出现次数的代码:
```vba
Sub CountHospitalID()
Dim ws1 As Worksheet, ws2 As Worksheet
Dim lastRow As Long, i As Long
Dim dict As Object
Dim hospitalID As String
' 获取sheet1和sheet2对象
Set ws1 = ThisWorkbook.Worksheets("sheet1")
Set ws2 = ThisWorkbook.Worksheets("sheet2")
' 获取sheet1中hospitalID列的最后一行行号
lastRow = ws1.Cells(ws1.Rows.Count, "A").End(xlUp).Row
' 使用字典对象统计hospitalID每个值的出现次数
Set dict = CreateObject("Scripting.Dictionary")
For i = 2 To lastRow
hospitalID = ws1.Cells(i, "A").Value
If Not dict.Exists(hospitalID) Then
dict(hospitalID) = 1
Else
dict(hospitalID) = dict(hospitalID) + 1
End If
Next i
' 将统计结果写入sheet2的新列中
ws2.Cells(1, "B").Value = "count"
For i = 2 To ws2.Cells(ws2.Rows.Count, "A").End(xlUp).Row
hospitalID = ws2.Cells(i, "A").Value
If dict.Exists(hospitalID) Then
ws2.Cells(i, "B").Value = dict(hospitalID)
Else
ws2.Cells(i, "B").Value = 0
End If
Next i
End Sub
```
这段代码首先获取名为“sheet1”和“sheet2”的工作表对象,然后使用字典对象统计“sheet1”中“hospitalID”每个值的出现次数。最后将统计结果写入到“sheet2”的新列“count”中。请注意,这段代码假设“sheet1”中“hospitalID”列从第二行开始,而“sheet2”中第一行已经有表头了。如需修改,请根据实际情况进行修改。
阅读全文