|
楼主 |
发表于 2023-5-17 15:59
|
显示全部楼层
[广告] Excel易用宝 - 提升Excel的操作效率 · Excel / WPS表格插件 ★ 免费下载 ★ ★ 使用帮助★
这个 是可以运行的代码,还是AI改的,需要的- Dim ws As Worksheet
- Dim data As Variant
- Dim uniqueValues As Object
- Dim currentColumn As Range
- Dim currentValue As Variant
- Dim NewWorkbook As Workbook
- Dim newWorksheet As Worksheet
- Dim FileName As String
- Dim i As Long, j As Long
- Dim rowCount As Long, colCount As Long
-
- ' 设置要拆分的表格工作表
- Set ws = ThisWorkbook.Worksheets("Sheet1") ' 修改为你的工作表名称
-
- ' 获取当前列
- Set currentColumn = Selection
-
- ' 获取数据范围
- rowCount = ws.Cells(ws.Rows.Count, currentColumn.Column).End(xlUp).Row ' 获取行数
- colCount = ws.Cells(1, ws.Columns.Count).End(xlToLeft).Column ' 获取列数
- data = ws.Range(ws.Cells(1, 1), ws.Cells(rowCount, colCount)).Value ' 将数据加载到数组
-
- ' 创建字典来存储唯一值
- Set uniqueValues = CreateObject("Scripting.Dictionary")
-
- ' 遍历列中的每个单元格,将唯一值添加到字典中
- For i = 1 To rowCount
- uniqueValues(data(i, currentColumn.Column)) = 1
- Next i
-
- ' 循环遍历唯一值
- For Each currentValue In uniqueValues.keys
- ' 创建一个新的工作簿并复制原始工作表
- Set NewWorkbook = Workbooks.Add
- Set newWorksheet = NewWorkbook.Sheets(1)
- newWorksheet.Name = "Sheet1"
-
- ' 复制标题行及格式
- ws.Rows(1).Copy Destination:=newWorksheet.Rows(1)
-
- ' 复制符合当前唯一值的行及格式
- j = 2 ' 从第二行开始复制数据
- For i = 1 To rowCount
- If data(i, currentColumn.Column) = currentValue Then
- ws.Rows(i).Copy Destination:=newWorksheet.Rows(j)
- j = j + 1
- End If
- Next i
-
- ' 保存新工作簿并关闭
- FileName = "Split_" & currentValue & ".xlsx" ' 设置文件名
- NewWorkbook.SaveAs FileName
- NewWorkbook.Close SaveChanges:=False
- Next currentValue
-
- ' 提示完成信息
- MsgBox "拆分完成!"
- End Sub
复制代码
拿去吧
|
|