2009-10-19 03:49:07 +0000 2009-10-19 03:49:07 +0000
9
9
Advertisement

エクセル2007で列を元にスプレッドシートを複数のファイルに分割することはできますか?

Advertisement

Excelで1つの列の内容に基づいて、大きなファイルを一連の小さなファイルに分割する方法はありますか?

例:私はすべての営業担当者の売上データのファイルを持っています。修正して返送するためにファイルを送信する必要がありますが、各営業担当者にファイル全体を送信する必要はありません(お互いのデータを変更したくないので)。ファイルは以下のようになっています。

salesdata.xls

RepName Customer ContactEmail
Adam Cust1 admin@cust1.com
Adam Cust2 admin@cust2.com
Bob Cust3 blah@cust3.com
etc...

この中から必要なものがあります。

salesdata_Adam.xls

RepName Customer ContactEmail
Adam Cust1 admin@cust1.com
Adam Cust2 admin@cust2.com

and salesdata_Bob.xls

Bob Cust3 blah@cust3.com

これを自動的に行うためにExcel 2007に組み込まれているものはありますか?

Advertisement
Advertisement

回答 (5)

8
8
8
2012-03-05 04:10:01 +0000

後世のために、この問題に取り組む別のマクロを紹介します。

このマクロは、指定された列を上から下に向かって処理し、新しい値が見つかるたびに新しいファイルに分割します。ブランクや繰り返し値は(総行数と同様に)一緒に保持されますが、列の値は**ソートされているか、一意である必要があります*。私は主にPivotTablesのレイアウトで動作するように設計しました( 値に変換された後 )。

なので、このままではコードを修正したり、名前付き範囲を用意したりする必要はありません。マクロは、処理する列と、処理を開始する行番号、つまりヘッダをスキップすることをユーザーに促すことから始まり、そこから進んでいきます。

セクションが特定されると、それらの値を別のシートにコピーするのではなく、ワークシート全体が新しいワークブックにコピーされ、セクションの下と上のすべての行が削除されます。これにより、印刷設定、条件付き書式設定、チャート、その他どんなものでも、その中にあるかもしれないものを保持することができ、各分割ファイルのヘッダを保持することができます。

ファイルは、セル値をファイル名にして、\Split\folderのサブフォルダに保存されます。まだ色々なドキュメントでのテストはしていませんが、サンプルファイルでは動作しています。試してみて、何か問題があれば教えてください。

マクロをエクセルのアドイン(xlam)として保存して、リボン/クイックアクセスツールバーのボタンにボタンを追加して、簡単にアクセスできるようにしました。

Public Sub SplitToFiles()

' MACRO SplitToFiles
' Last update: 2019-05-28
' Author: mtone
' Version 1.2
' Description:
' Loops through a specified column, and split each distinct values into a separate file by making a copy and deleting rows below and above
'
' Note: Values in the column should be unique or sorted.
'
' The following cells are ignored when delimiting sections:
' - blank cells, or containing spaces only
' - same value repeated
' - cells containing "total"
'
' Files are saved in a "Split" subfolder from the location of the source workbook, and named after the section name.

Dim osh As Worksheet ' Original sheet
Dim iRow As Long ' Cursors
Dim iCol As Long
Dim iFirstRow As Long ' Constant
Dim iTotalRows As Long ' Constant
Dim iStartRow As Long ' Section delimiters
Dim iStopRow As Long
Dim sSectionName As String ' Section name (and filename)
Dim rCell As Range ' current cell
Dim owb As Workbook ' Original workbook
Dim sFilePath As String ' Constant
Dim iCount As Integer ' # of documents created

iCol = Application.InputBox("Enter the column number used for splitting", "Select column", 2, , , , , 1)
iRow = Application.InputBox("Enter the starting row number (to skip header)", "Select row", 2, , , , , 1)
iFirstRow = iRow

Set osh = Application.ActiveSheet
Set owb = Application.ActiveWorkbook
iTotalRows = osh.UsedRange.Rows.Count
sFilePath = Application.ActiveWorkbook.Path

If Dir(sFilePath + "\Split", vbDirectory) = "" Then
    MkDir sFilePath + "\Split"
End If

'Turn Off Screen Updating Events
Application.EnableEvents = False
Application.ScreenUpdating = False

Do
    ' Get cell at cursor
    Set rCell = osh.Cells(iRow, iCol)
    sCell = Replace(rCell.Text, " ", "")

    If sCell = "" Or (rCell.Text = sSectionName And iStartRow <> 0) Or InStr(1, rCell.Text, "total", vbTextCompare) <> 0 Then
        ' Skip condition met
    Else
        ' Found new section
        If iStartRow = 0 Then
            ' StartRow delimiter not set, meaning beginning a new section
            sSectionName = rCell.Text
            iStartRow = iRow
        Else
            ' StartRow delimiter set, meaning we reached the end of a section
            iStopRow = iRow - 1

            ' Pass variables to a separate sub to create and save the new worksheet
            CopySheet osh, iFirstRow, iStartRow, iStopRow, iTotalRows, sFilePath, sSectionName, owb.fileFormat
            iCount = iCount + 1

            ' Reset section delimiters
            iStartRow = 0
            iStopRow = 0

            ' Ready to continue loop
            iRow = iRow - 1
        End If
    End If

    ' Continue until last row is reached
    If iRow < iTotalRows Then
            iRow = iRow + 1
    Else
        ' Finished. Save the last section
        iStopRow = iRow
        CopySheet osh, iFirstRow, iStartRow, iStopRow, iTotalRows, sFilePath, sSectionName, owb.fileFormat
        iCount = iCount + 1

        ' Exit
        Exit Do
    End If
Loop

'Turn On Screen Updating Events
Application.ScreenUpdating = True
Application.EnableEvents = True

MsgBox Str(iCount) + " documents saved in " + sFilePath

End Sub

Public Sub DeleteRows(targetSheet As Worksheet, RowFrom As Long, RowTo As Long)

Dim rngRange As Range
Set rngRange = Range(targetSheet.Cells(RowFrom, 1), targetSheet.Cells(RowTo, 1)).EntireRow
rngRange.Select
rngRange.Delete

End Sub

Public Sub CopySheet(osh As Worksheet, iFirstRow As Long, iStartRow As Long, iStopRow As Long, iTotalRows As Long, sFilePath As String, sSectionName As String, fileFormat As XlFileFormat)
     Dim ash As Worksheet ' Copied sheet
     Dim awb As Workbook ' New workbook

     ' Copy book
     osh.Copy
     Set ash = Application.ActiveSheet

     ' Delete Rows after section
     If iTotalRows > iStopRow Then
         DeleteRows ash, iStopRow + 1, iTotalRows
     End If

     ' Delete Rows before section
     If iStartRow > iFirstRow Then
         DeleteRows ash, iFirstRow, iStartRow - 1
     End If

     ' Select left-topmost cell
     ash.Cells(1, 1).Select

     ' Clean up a few characters to prevent invalid filename
     sSectionName = Replace(sSectionName, "/", " ")
     sSectionName = Replace(sSectionName, "\", " ")
     sSectionName = Replace(sSectionName, ":", " ")
     sSectionName = Replace(sSectionName, "=", " ")
     sSectionName = Replace(sSectionName, "*", " ")
     sSectionName = Replace(sSectionName, ".", " ")
     sSectionName = Replace(sSectionName, "?", " ")
     sSectionName = Strings.Trim(sSectionName)

     ' Save in same format as original workbook
     ash.SaveAs sFilePath + "\Split\" + sSectionName, fileFormat

     ' Close
     Set awb = ash.Parent
     awb.Close SaveChanges:=False
End Sub
6
6
6
2009-10-19 03:53:42 +0000

私の知る限りでは、データを分割して自動的にファイルセットに保存するマクロ以外の方法はありません。VBAの方が簡単でしょう。

Update 私の提案を実装しました。これは、名前付き範囲'RepList'に定義されているすべての名前をループします。名前付き範囲は、=OFFSET(Names!$A$2,0,0,COUNTA(Names!$A:$A)-1,1)

モジュールの形式の動的な名前付き範囲です。

Option Explicit

'Split sales data into separate columns baed on the names defined in
'a Sales Rep List on the 'Names' sheet.
Sub SplitSalesData()
    Dim wb As Workbook
    Dim p As Range

    Application.ScreenUpdating = False

    For Each p In Sheets("Names").Range("RepList")
        Workbooks.Add
        Set wb = ActiveWorkbook
        ThisWorkbook.Activate

        WritePersonToWorkbook wb, p.Value

        wb.SaveAs ThisWorkbook.Path & "\salesdata_" & p.Value
        wb.Close
    Next p
    Application.ScreenUpdating = True
    Set wb = Nothing
End Sub

'Writes all the sales data rows belonging to a Person
'to the first sheet in the named SalesWB.
Sub WritePersonToWorkbook(ByVal SalesWB As Workbook, _
                          ByVal Person As String)
    Dim rw As Range
    Dim personRows As Range 'Stores all of the rows found
                                'containing Person in column 1
    For Each rw In UsedRange.Rows
        If Person = rw.Cells(1, 1) Then
            If personRows Is Nothing Then
                Set personRows = rw
            Else
                Set personRows = Union(personRows, rw)
            End If
        End If
    Next rw

    personRows.Copy SalesWB.Sheets(1).Cells(1, 1)
    Ser personRows = Nothing
End Sub

このワークブック には、コードと名前付き範囲が含まれています。コードは「売上データ」シートの一部です。

2
Advertisement
2
2
2009-10-19 03:59:17 +0000
Advertisement

もし他の誰かがこの方法を素早く行う正しい方法で回答した場合は、この回答を無視してください。

個人的には、Excelを使っていて、何かをするための複雑な方法や、二度と使うことがないのにすべてを実行してくれるような大げさな方程式を探すのに多くの時間(時には何時間も)を費やしていることに気付きます。


もしあなたが一握りの人しかいないのであれば、私がお勧めするのは、すべてのデータをハイライトして、データタブに移動し、ソートボタンをクリックすることです。

ソートする列を選択することができます。

VBAや他のツールを使って解決策を思いつくかもしれませんが、実際には何時間もの作業が必要になります。

また、この種のことはsharepoint + excelサービスでもできると思いますが、それはこの種のことのための上から目線の解決策です。

1
1
1
2009-10-19 20:13:28 +0000

さて、ここでVBAの最初のカットです。このように呼びます。

SplitIntoFiles Range("A1:N1"), Range("A2:N2"), Range("B2"), "Split File - "
Option Explicit
Public Sub SplitIntoFiles(headerRange As Range, startRange As Range, keyCell As Range, filenameBase As String)

    ' assume the keyCell column is already sorted

    ' start a new workbook
    Dim wb As Workbook
    Dim ws As Worksheet

    Set wb = Application.Workbooks.Add
    Set ws = wb.ActiveSheet

    Dim destRange As Range
    Set destRange = ws.Range("A1")

    ' copy header
    headerRange.Copy destRange
    Set destRange = destRange.Offset(headerRange.Rows.Count)

    Dim keyValue As Variant
    keyValue = ""

    While keyCell.Value <> ""

        ' if we've got a new key, save the file and start a new one
        If (keyValue <> keyCell.Value) Then
        If keyValue <> "" Then
            'TODO: remove non-filename chars from keyValue
            wb.SaveAs filenameBase & CStr(keyValue)
            wb.Close False
            Set wb = Application.Workbooks.Add
            Set ws = wb.ActiveSheet
            Set destRange = ws.Range("A1")

            ' copy header
            headerRange.Copy destRange
            Set destRange = destRange.Offset(headerRange.Rows.Count)

            End If
        End If

        keyValue = keyCell.Value

        ' copy the contents of this row to the new sheet
        startRange.Copy destRange

        Set keyCell = keyCell.Offset(1)
        Set destRange = destRange.Offset(1)
        Set startRange = startRange.Offset(1)
    Wend

    ' save residual
    'TODO: remove non-filename chars from keyValue
    wb.SaveAs filenameBase & CStr(keyValue)
    wb.Close

End Sub

ここで、A1:N1はヘッダ行、A2:N2はデータの最初の行、B2は事前にソートされたキー列の最初のセルです。最後の引数はファイル名のプレフィックスです。キーは保存前にこれに付加されます。

免責事項: このコードは厄介です。

0x1&

-2
Advertisement
-2
-2
2012-12-11 08:32:17 +0000
Advertisement

私は名前でソートして、送信したい2枚目のエクセルシートにそのまま貼り付けています。エクセルは表示されている行だけを貼り付けて、隠れている行も貼り付けません。あと、更新してほしいセル以外は保護しています(笑)

Advertisement

関連する質問

6
7
13
9
10
Advertisement
Advertisement