0

I have a spreadsheet which I want to split to separate spreadsheets for each department there are more then the departments shown and I want the .xls files for each to be save with the department name

The department field is column D.

i.e. I would like an .xls file for each with only the records for department 1, department 2, and so on.

Unfortunately I am unable to post a screenshot of the spreadsheet as my rep isn't good enough yet.

What VBA code would I use to do this?

4

1 に答える 1

2

これはあなたが必要とすることをするはずです。それを実行して列文字を指定すると、その列に基づいて作成されます。それ以外の場合は、指定したようにデフォルトで D になります。

Sub SplitWorkbook(Optional colLetter As String, Optional SavePath As String)
If colLetter = "" Then colLetter = "D"
Dim lastValue As String
Dim hasHeader As Boolean
Dim wb As Workbook
Dim c As Range
Dim currentRow As Long
hasHeader = True 'Indicate true or false depending on if sheet  has header row.

If SavePath = "" Then SavePath = ThisWorkbook.Path
'Sort the workbook.
ThisWorkbook.Worksheets(1).Sort.SortFields.Add Key:=Range(colLetter & ":" & colLetter), _
    SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal
With ThisWorkbook.Worksheets(1).Sort
    .SetRange Cells
    If hasHeader Then ' Was a header indicated?
        .Header = xlYes
    Else
        .Header = xlNo
    End If
    .MatchCase = False
    .Orientation = xlTopToBottom
    .SortMethod = xlPinYin
    .Apply
End With

For Each c In ThisWorkbook.Sheets(1).Range("D:D")
    If c.Value = "" Then Exit For
    If c.Row = 1 And hasHeader Then
    Else
        If lastValue <> c.Value Then
            If Not (wb Is Nothing) Then
                wb.SaveAs SavePath & "\" & lastValue & ".xls"
                wb.Close
            End If
            lastValue = c.Value
            currentRow = 1
            Set wb = Application.Workbooks.Add
        End If
        ThisWorkbook.Sheets(1).Rows(c.Row & ":" & c.Row).Copy
        wb.Sheets(1).Cells(Rows.Count, 1).End(xlUp).Select
        wb.Sheets(1).Paste

    End If
Next
If Not (wb Is Nothing) Then
    wb.SaveAs SavePath & "\" & lastValue & ".xls"
    wb.Close
End If
End Sub

これにより、これを実行するワークブックと同じフォルダーまたは指定したパスに別のワークブックが生成されます。

于 2012-04-13T00:58:25.057 に答える