以下代码,先另存为 “拆分sheet.bas”文件,
程序代码:
Attribute VB_Name = "按某列把Sheet拆分为多个文件"
'按照某列的选项分成多个Excel表格,总提示报错,请帮忙看一下,谢谢
'说明,A、必须保证有一个Sheet名为“数据源”!其余无问题,可以运行
'B、在运行的过程中,会删除 除“数据源”之外的所有Sheet
'A、B 由5hawn根据实际情况,作了修改。
'此程序的特点:在拆分的过程中,会保留原来的格式(字体、颜色等)
Sub CutSheetByColumn()
Dim myRange As Variant
Dim myArray
Dim titleRange As Range
Dim title As String, shtName As String
Dim columnNum As Integer, shtCount As Integer
myRange = Application.InputBox(prompt:="请选择标题行:", Type:=8)
myArray = WorksheetFunction.Transpose(myRange)
Set titleRange = Application.InputBox(prompt:="请选择拆分的表头,必须是第一行,且为一个单元格,如:“姓名”", Type:=8)
title = titleRange.Value
shtName = titleRange.Areas.Parent.Worksheet.Name
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 <> "数据源" Then
' Sheets(i).Delete
' End If
' Next i
Set d = CreateObject("Scripting.Dictionary")
Myr = Worksheets(shtName).UsedRange.Rows.Count
Arr = Worksheets(shtName).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 [" & shtName & "$] 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(shtName).Activate
Sheets(shtName).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
shtCount = shtCount + 1
Next i
conn.Close
Set conn = Nothing
Application.DisplayAlerts = True
Application.ScreenUpdating = True
MsgBox "以[" & title & "]列拆分Sheet[" & shtName & "],完成。共拆为[" & shtCount & "]个文件。", vbOKOnly, "提示:"
End Sub