写一个vba代码实现以下需求,1.在工作簿的最后批量新增工作表2.工作表以单元格E2到E最后一行的值命名,E有几行就新建几个工作表3.将名为sip统计的工作表的C列筛选,新建的工作表名称与C列值匹配一致,则将匹配一致的行的A列到C列复制到对应的新建工作表的A2
时间: 2024-02-17 17:00:54 浏览: 110
以下是实现您需求的 VBA 代码:
```vb
Sub AddNewSheets()
Dim lastRow As Long
Dim i As Long
Dim ws As Worksheet
Dim newWs As Worksheet
Dim wsName As String
'获取当前活动工作表
Set ws = ActiveSheet
'获取单元格 E2 到 E 最后一行的值
lastRow = ws.Cells(Rows.Count, 5).End(xlUp).Row
'循环新建工作表
For i = 2 To lastRow
wsName = ws.Cells(i, 5).Value
'判断工作表是否已经存在,如果不存在则新建
If Not SheetExists(wsName) Then
Set newWs = ThisWorkbook.Sheets.Add(After:=ThisWorkbook.Sheets(ThisWorkbook.Sheets.Count))
newWs.Name = wsName
End If
Next i
'筛选名为“sip统计”的工作表的 C 列
Set ws = ThisWorkbook.Sheets("sip统计")
lastRow = ws.Cells(Rows.Count, 3).End(xlUp).Row
ws.Range("C1:C" & lastRow).AutoFilter Field:=1, Criteria1:="<>", Operator:=xlFilterValues
'将匹配一致的行的 A 到 C 列复制到对应的新建工作表的 A2
For i = 2 To lastRow
wsName = ws.Cells(i, 3).Value
If SheetExists(wsName) Then
Set newWs = ThisWorkbook.Sheets(wsName)
With ws.Range("A" & i & ":C" & i)
.Copy newWs.Range("A" & newWs.Cells(Rows.Count, 1).End(xlUp).Row + 1)
End With
End If
Next i
'取消筛选
ws.AutoFilterMode = False
MsgBox "新建工作表完成"
End Sub
Function SheetExists(sheetName As String) As Boolean
Dim sheet As Worksheet
On Error Resume Next
Set sheet = ThisWorkbook.Sheets(sheetName)
SheetExists = Not sheet Is Nothing
End Function
```
您只需要将其复制到 VBA 编辑器中,然后在工作簿中按下快捷键 Alt + F8,选中 AddNewSheets 并点击“运行”即可。
阅读全文