说明

此代码是很久之前保存的了,想不起来在哪里下下来的了 ,在此感谢代码作者。

代码

Public Sub 根据列拆分表()
    Dim arr, d As Object, k, t, i&, lc%, rng As Range, c%
    
    Dim objShell
    Dim objFolder
    Dim strPath As String
        
    c = Application.InputBox("请输入拆分列的列号,列号应为数字,例:A 列应填写 1,C 列应填写 3。", , 4, , , , , 1)
    If c = 0 Then Exit Sub
    Application.ScreenUpdating = False
    Application.DisplayAlerts = False
    arr = [a1].CurrentRegion
    lc = UBound(arr, 2)
    Set rng = [a1].Resize(, lc)
    Set d = CreateObject("scripting.dictionary")
    For i = 2 To UBound(arr)
        If Not d.Exists(arr(i, c)) Then
            Set d(arr(i, c)) = Cells(i, 1).Resize(1, lc)
        Else
            Set d(arr(i, c)) = Union(d(arr(i, c)), Cells(i, 1).Resize(1, lc))
        End If
    Next
    k = d.Keys
    t = d.Items
    
    Set objShell = CreateObject("Shell.Application")
    Set objFolder = objShell.BrowseForFolder(0, "选择拆分文件的存放位置/文件夹", 0, 0)
    If Not objFolder Is Nothing Then
        strPath = objFolder.self.Path
    Else
        strPath = ""
    End If
        Set objFolder = Nothing
        Set objShell = Nothing
    
    For i = 0 To d.Count - 1
        With Workbooks.Add(xlWBATWorksheet)
            rng.Copy .Sheets(1).[a1]
            t(i).Copy .Sheets(1).[a2]
            .SaveAs Filename:=strPath & "\" & k(i) & ".xlsx"
            .Close
        End With
    Next
    Application.DisplayAlerts = True
    Application.ScreenUpdating = True
    MsgBox "拆分完成!"
End Sub
最后修改:2020 年 10 月 13 日 09 : 16 PM
如果觉得文章帮助了您,您可以随意赞赏。