# VBA之根据筛选条件创建新的工作表完整版

Sub chaifenshuju()

Dim sht As Worksheet
Dim k, i, j As Integer
Dim irow As Integer '这个说的是一共多少行
Dim l As Integer

l = InputBox(“请输入你要按哪列分”)

'删除无意义的表
If Sheets.Count > 1 Then
For Each sht1 In Sheets
If sht1.Name <> “数据” Then
sht1.Delete
End If
Next
End If

irow = Sheet1.Range(“a65536”).End(xlUp).Row
'拆分表
For i = 2 To irow
k = 0
For Each sht In Sheets
If sht.Name = Sheet1.Cells(i, l) Then
k = 1
End If
Next

If k = 0 Then
Sheets(Sheets.Count).Name = Sheet1.Cells(i, l)
End If


Next
'拷贝数据

For j = 2 To Sheets.Count
Sheet1.Range(“a1:f” & irow).AutoFilter Field:=l, Criteria1:=Sheets(j).Name
Sheet1.Range(“a1:f” & irow).Copy Sheets(j).Range(“a1”)
Next

Sheet1.Range(“a1:f” & irow).AutoFilter

Sheet1.Select

MsgBox “已处理完毕”

End Sub

1.定义总行数
Dim irow As Integer '这个说的是一共多少行
irow = Sheet1.Range(“a65536”).End(xlUp).Row

2.根据用户的选择来进行筛选,这里要用到交互式弹窗,把用户输入的数字作为筛选的列
l = InputBox(“请输入你要按哪列分”)
3.删除无意义的表
If Sheets.Count > 1 Then
For Each sht1 In Sheets
If sht1.Name <> “数据” Then
sht1.Delete
End If
Next
End If

4.拆分表
irow = Sheet1.Range(“a65536”).End(xlUp).Row
'拆分表
For i = 2 To irow
k = 0
For Each sht In Sheets
If sht.Name = Sheet1.Cells(i, l) Then
k = 1
End If
Next
If k = 0 Then
Sheets(Sheets.Count).Name = Sheet1.Cells(i, l)
End If

cell的第一个参数是行数,第二个参数是列数

5.拷贝数据
For j = 2 To Sheets.Count
Sheet1.Range(“a1:f” & irow).AutoFilter Field:=l, Criteria1:=Sheets(j).Name
Sheet1.Range(“a1:f” & irow).Copy Sheets(j).Range(“a1”)
Next

Sheet1.Range(“a1:f” & irow).AutoFilter

Sheet1.Select

MsgBox “已处理完毕”

©️2019 CSDN 皮肤主题: 大白 设计师: CSDN官方博客