按照某列属性拆分Excel文件

Posted RS&Hydrology

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了按照某列属性拆分Excel文件相关的知识,希望对你有一定的参考价值。

1.利用Excel中开发工具[https://blog.csdn.net/ntotl/article/details/79141314](https://blog.csdn.net/ntotl/article/details/79141314)
(1)打开需要拆分的Excel文件,Alt+F11打开VBE窗口;
(2)插入——模块,输入代码:

Sub 保留表头拆分数据为若干新工作簿()
    Dim arr, d As Object, k, t, i&, lc%, rng As Range, c%
    c = Application.InputBox("请输入拆分列号", , 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
    For i = 0 To d.Count - 1
        With Workbooks.Add(xlWBATWorksheet)
            rng.Copy .Sheets(1).[a1]
            t(i).Copy .Sheets(1).[a2]
            .SaveAs Filename:=ThisWorkbook.Path & "\\" & k(i) & ".xls"
            .Close
        End With
    Next
    Application.DisplayAlerts = True
    Application.ScreenUpdating = True
    MsgBox "完毕"
End Sub

转自https://blog.csdn.net/ntotl/article/details/79141314代码。

注意分拆分后的Excel文件格式为xls。
(3)开发工具——插入——按钮


会形成一个按钮,点击该窗体控件,加载刚刚建立的宏,设置拆分序列号,即根据哪一列属性拆分(class)。
(4)完成操作

2.VBA批量将xls文件转换成xlsx文件
(1)新建一个Excel(与需要转换文件同一目录);
(2)输入代码:

Sub xls2xlsx()
Dim FilePath, MyFile, iPath, Name, OutPath As String
iPath = ThisWorkbook.Path
OutPath = Dir(iPath & "\\xlsx", vbDirectory)
If OutPath = "" Then
    MkDir (iPath & "\\xlsx")
End If
MyFile = Dir(iPath & "\\*.xls")

If MyFile <> "" Then
Do
    On Error Resume Next
    If MyFile = ThisWorkbook.Name Then MyFile = Dir
    Workbooks.Open (iPath & "\\" & MyFile)
    MyFile = Replace(MyFile, ".xls", ".xlsx")
    Name = "\\" & MyFile
    FilePath = iPath & "\\xlsx" & Name
    Application.ScreenUpdating = False
    ActiveWorkbook.SaveAs Filename:=FilePath, FileFormat:=xlOpenXMLWorkbook, CreateBackup:=False
    Workbooks(MyFile).Close True
    Application.ScreenUpdating = True
    MyFile = Dir
Loop While MyFile <> ""
End If
End Sub

运行结束!

以上是关于按照某列属性拆分Excel文件的主要内容,如果未能解决你的问题,请参考以下文章

1分钟实现:按某列内容分类汇总,分页打印 Excel 表格

向vb 高手求助代码编程:菜单中打开txt或excel数据表文件,求某列中几个数求平均,找出并输出均值附近数据

数据处理小工具:Excel 批量数据文件拆分/整合器...

怎样将一个excel表格的多个sheet拆分成多个excel表

如何将excel某列内相同内容填充相同单元格底色?

如何定位DataGridView中的某行中的某列