一個新的工作簿的一個新的標準模塊中的代碼粘貼波紋管
Option Explicit
Public Sub SplitPlantNumbers()
Const SRC = "D:\Original.xlsx"
Const DST = "D:\"
Const SRC_WS = "Recipes"
Const DST_WS = "Tabelle1"
Const PN = "Plant Number-"
Const DT = "yyyy-mm-dd-hh-mm-ss"
Dim wbSrc As Workbook, wsSrc As Worksheet, urSrc As Variant
Dim wbDst As Workbook, wsDst As Worksheet, i As Long, d As Object
Application.DisplayAlerts = False
Application.ScreenUpdating = False
Set wbSrc = Workbooks.Open(SRC)
If wbSrc Is Nothing Then
MsgBox "Invalid source file: " & SRC, , "File Not Found"
Exit Sub
End If
If Not WsExists(wbSrc, SRC_WS) Then
MsgBox "Invalid sheet name: " & SRC_WS, , "Src file: " & SRC
Exit Sub
End If
Set wsSrc = wbSrc.Worksheets(SRC_WS)
urSrc = wsSrc.UsedRange
Set wbDst = ThisWorkbook
Set wsDst = GetDstWs(wbDst, DST_WS)
If UBound(urSrc) > 1 Then
wsSrc.AutoFilterMode = False
Set d = CreateObject("Scripting.Dictionary")
For i = 2 To UBound(urSrc)
d(urSrc(i, 1)) = urSrc(i, 1) '--------------- get uniques
Next
For i = 1 To d.Count '--------------- create files
With wsSrc.UsedRange
.AutoFilter Field:=1, Criteria1:=d(i)
.Copy wsDst.Cells(1)
End With
wbDst.SaveAs Filename:=DST & PN & d(i) & " - " & Format(Now, DT)
wsDst.UsedRange.EntireRow.Delete
Next
wsSrc.AutoFilterMode = False
wbSrc.Close False
End If
Application.DisplayAlerts = True
Application.ScreenUpdating = True
End Sub
Private Function GetDstWs(ByRef wb As Workbook, ByVal wsName As String) As Worksheet
Dim ws As Worksheet
If Not wb Is Nothing And Len(wsName) > 0 Then
If wb.Worksheets.Count > 1 Or _
(wb.Worksheets.Count = 1 And wb.Worksheets(1).Name <> wsName) Then
For Each ws In wb.Worksheets
If ws.Name = wsName Then
ws.Delete
Exit For
End If
Next
Set GetDstWs = wb.Worksheets.Add(Before:=wb.Worksheets(1))
GetDstWs.Name = wsName
For Each ws In wb.Worksheets
If ws.Name <> wsName Then ws.Delete
Next
Else
Set GetDstWs = wb.Worksheets(1)
End If
End If
End Function
Private Function WsExists(ByRef wb As Workbook, ByVal wsName As String) As Boolean
Dim ws As Worksheet
If Not wb Is Nothing And Len(wsName) > 0 Then
For Each ws In wb.Worksheets
If ws.Name = wsName Then
WsExists = True
Exit Function
End If
Next
End If
End Function
它將在d生成新的文件:像
Plant Number-1 - 2017-09-25-19-44-33.xlsm
Plant Number-2 - 2017-09-25-19-44-34.xlsm
Plant Number-3 - 2017-09-25-19-44-35.xlsm
等,在D:\Original.xlsx
檢查此鏈接每個工廠https://www.extendoffice.com/documents/excel/1174-excel-split-data- into-multiple-worksheets-based-on-column.html – Maddy