案例
題目:
excel將下面叫做“數(shù)據(jù)”的工作表根據(jù)分類條件拆分成多個sheet工作表,表名為分類條件。
結(jié)果如下:
分析:
注意:執(zhí)行這段代碼前必須選中總表即你要拆分的表,否則數(shù)據(jù)會遭到破壞
代碼:
Sub chaifen()
Dim i As Integer
Dim j, k, irow, count As Integer
Dim sht As Worksheet
Dim sht1 As Worksheet
Dim x As Integer
Dim sht0 As Worksheet
Set sht0 = ActiveSheet
x = InputBox("請選擇你要按哪列分,第幾列就填幾")
'執(zhí)行分表前刪除多余的表
Application.DisplayAlerts = False
If Sheets.count > 1 Then
For Each sht1 In Sheets
If sht1.Name <> sht0.Name Then
sht1.Delete
End If
Next
End If
Application.DisplayAlerts = True
'獲取sheet1總行數(shù)
irow = sht0.Range("a65536").End(xlUp).Row
For i = 2 To irow
'初始化k
k = 0
For Each sht In Sheets
'判斷是否已存在表名
If sht.Name = sht0.Cells(i, x) Then
k = 1
End If
Next
'如果不存在表名就新建一個表
If k = 0 Then
Sheets.Add after:=Sheets(Sheets.count)
Sheets(Sheets.count).Name = sht0.Cells(i, x)
End If
'篩選拷貝數(shù)據(jù)
For j = 2 To Sheets.count
sht0.Range("a1:f" & irow).AutoFilter field:=x, Criteria1:=Sheets(j).Name
sht0.Range("a1:f" & irow).Copy Sheets(j).Range("a1")
'關(guān)閉篩選
sht0.Range("a1:f" & irow).AutoFilter
Next
Next
sht0.Select
End Sub
注意:執(zhí)行這段代碼前必須選中總表即你要拆分的表,否則數(shù)據(jù)會遭到破壞
這段案例代碼的知識點(diǎn)有:
聯(lián)系客服