Excel按某列的字段条件将工作表拆分成多个工作簿
Excel按某列的字段条件将工作表拆分成多个工作簿并按字段名称命名工作簿,之前我们介绍过按工作表名称不同拆分成一个个独立的EXCEL文件:https://www.bnxb.com/excel/27087.html
这里介绍另外一种用法
有时候我们在做表格需要将表格中同一个名称的内容,按名称分别存到电脑上,比如我有个表有不同个客户名称,对应的订货情况,我需要按客户名称不同来拆分成一个个客户单独的EXCEL文件,用于发给客户核对,这个时候就可以用到这个宏
使用方法:
这里以将不同客户的订货信息拆分到不同Excel为例:
在你要进行拆分的表格中(这个表格文件名:货品订货统计.xlsx,工作表名称Sheet1)依次点击-开发工具-Visual Basic(或者按ALT+F11)
在你的工作表名称上面点右键选择-插入-模块
然后将下面的宏复制黏贴到框中
Sub Bnxbcom() Dim myRange As Variant Dim myArray Dim titleRange As Range Dim title As String Dim columnNum As Integer myRange = Application.InputBox(prompt:="请选择标题行:", Type:=8) myArray = WorksheetFunction.Transpose(myRange) Set titleRange = Application.InputBox(prompt:="请选择拆分的表头,必须是第一行,且为一个单元格,如:“姓名”", Type:=8) title = titleRange.Value columnNum = titleRange.Column Application.ScreenUpdating = False Application.DisplayAlerts = False Dim i&, Myr&, Arr, num& Dim d, k For i = Sheets.Count To 1 Step -1 If Sheets(i).Name <> "Sheet1" Then Sheets(i).Delete End If Next i Set d = CreateObject("Scripting.Dictionary") Myr = Worksheets("Sheet1").UsedRange.Rows.Count Arr = Worksheets("Sheet1").Range(Cells(2, columnNum), Cells(Myr, columnNum)) For i = 1 To UBound(Arr) d(Arr(i, 1)) = "" Next k = d.keys For i = 0 To UBound(k) Set conn = CreateObject("adodb.connection") conn.Open "provider=microsoft.jet.oledb.4.0;extended properties=excel 8.0;data source=" & ThisWorkbook.FullName Sql = "select * from [Sheet1$] where " & title & " = '" & k(i) & "'" Dim Nowbook As Workbook Set Nowbook = Workbooks.Add With Nowbook With .Sheets(1) .Name = k(i) For num = 1 To UBound(myArray) .Cells(1, num) = myArray(num, 1) Next num .Range("A2").CopyFromRecordset conn.Execute(Sql) End With End With ThisWorkbook.Activate Sheets(1).Cells.Select Selection.Copy Workbooks(Nowbook.Name).Activate ActiveSheet.Cells.Select Selection.PasteSpecial Paste:=xlPasteFormats, Operation:=xlNone, _ SkipBlanks:=False, Transpose:=False Application.CutCopyMode = False Nowbook.SaveAs ThisWorkbook.Path & "\" & k(i) Nowbook.Close True Set Nowbook = Nothing Next i conn.Close Set conn = Nothing Application.DisplayAlerts = True Application.ScreenUpdating = True End Sub
如下
然后关闭代码窗口,返回表格
按ALT+F8或者依次点击开发工具-宏-执行
然后按提示选择固定的标题行
还有要拆分的字段
等待执行完毕,这个文件存放的目录下就多了很多个按客户名称命名的表格了
顶(7)
踩(0)
- 最新评论