vba利用自动筛选按任意列拆分成多工作表

Option Explicit

Sub main()
    Dim colNo As Integer, sht As Worksheet, lastRow As Long, i As Long, flag As Boolean
    colNo = InputBox("col no:")
        
    Excel.Application.DisplayAlerts = False
    For Each sht In Sheets
        If sht.Name <> Sheet1.Name Then sht.Delete
    Next
    Excel.Application.DisplayAlerts = True
    
    lastRow = Sheet1.Range("A1000000").End(xlUp).Row
    
    For i = 2 To lastRow
        flag = False
        For Each sht In Sheets
            If sht.Name = Sheet1.Cells(i, colNo) Then
                flag = True
                Exit For
            End If
        Next
        
        If Not flag Then
            Sheets.Add(after:=Sheets(Sheets.Count)).Name = Sheet1.Cells(i, colNo).Value
            Sheet1.UsedRange.AutoFilter field:=colNo, Criteria1:=Sheet1.Cells(i, colNo).Value
            Sheet1.UsedRange.Copy Sheets(Sheets.Count).[A1]
        End If
    Next
    
    Sheet1.UsedRange.AutoFilter
    
End Sub

 

Option Explicit

Sub main()
    Dim lineNo As Integer, keys, dict, i As Integer
    lineNo = InputBox("input line no")
    
    Set dict = GetItems(Sheet1, lineNo)
    keys = dict.keys
    Call DeleteSheets
    
    For i = 0 To dict.Count - 1
        Sheets.Add after:=Sheets(Sheets.Count)
        Sheets(Sheets.Count).Name = keys(i)
        
        Sheet1.UsedRange.AutoFilter field:=lineNo, Criteria1:=keys(i)
        Sheet1.UsedRange.Copy Sheets(Sheets.Count).Range("A1")
        
    Next
    
    Sheet1.UsedRange.AutoFilter
    
End Sub

Function GetItems(sht As Worksheet, lineNo As Integer)
    Dim d As Object, i As Integer
    Set d = CreateObject("Scripting.Dictionary")
    For i = 2 To sht.Range("A65536").End(xlUp).Row
        If Not d.exists(sht.Cells(i, lineNo).Value) Then
             d.Add Key:=sht.Cells(i, lineNo).Value, Item:=sht.Cells(i, lineNo).Value
        End If
    Next
    Set GetItems = d
End Function


Sub DeleteSheets()
    Dim i As Integer
    Excel.Application.DisplayAlerts = False
    For i = Sheets.Count To 2 Step -1
        Sheets(i).Delete
    Next
    Excel.Application.DisplayAlerts = True
End Sub

 

  • 0
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值