次のマクロは、新しいワークブックの単一のワークシートとして各ワークシートを保存します:
Option Explicit
Public Sub SplitFile()
Const dstTopLevelPath As String = "C:\MyData\AgencyStuff"
Dim dstFolder As String
Dim dstFilename As String
Dim dstWB As Workbook
Dim dstWS As Worksheet
Dim srcWB As Workbook
Dim srcWS As Worksheet
Dim Agency As String
'Ensure the destination path exists
If Dir(dstTopLevelPath, vbDirectory) = "" Then
MsgBox dstTopLevelPath & " doesn't exist - please create it before running this macro"
End
End If
Set srcWB = ActiveWorkbook
For Each srcWS In srcWB.Worksheets
'Get the Agency name
'(use this line if the Agency name is in cell A2 of each worksheet)
Agency = srcWS.Range("A2").Value
'(use this line if the Agency name is the actual worksheet name)
'Agency = srcWS.Name
'Create the destination path
dstFolder = dstTopLevelPath & "\" & Agency
'Create the destination file name
'(use this line if you want the new workbooks to have a name equal to the agency name)
dstFilename = dstFolder & "\" & Agency & ".xlsx"
'(use this line if you want the new workbooks to have the same name as your existing workbook)
'(Note: If your existing workbook is called "xyz.xlsm", the new workbooks will have a ".xlsm"
' extension, even though there won't be any macros in them.)
'dstFilename = dstFolder & "\" & srcWB.Name
'(use this line if you want the new workbooks to have a fixed name)
'dstFilename = dstFolder & "\data.xlsx"
'Create a new workbook
Set dstWB = Workbooks.Add
'Copy the current sheet to the new workbook
srcWS.Copy Before:=dstWB.Sheets(1)
'Get rid of any sheets automatically created in the new workbook ("Sheet1", "Sheet2", etc)
For Each dstWS In dstWB.Worksheets
If dstWS.Name <> srcWS.Name Then
Application.DisplayAlerts = False
dstWS.Delete
Application.DisplayAlerts = True
End If
Next
'Ensure the new location exists, and create it if it doesn't
If Dir(dstFolder, vbDirectory) = "" Then
MkDir dstFolder
End If
'Save the new workbook to the required location
dstWB.SaveAs dstFilename
'Close the new workbook
dstWB.Close
Next
MsgBox "Finished"
End Sub
(これは、「Sheet1」、「Sheet2」などの名前を持つソースワークシートがないことを前提としています)
「ワークシート」を意味すると思われるときに「ブック」を使用しているようですので、少し混乱しますか?あなたの質問を更新してより明確にするのに役立ちますか?ブック= Excelファイル、ワークシート=ブック内の特定のタブ –
質問を更新しました –