我有一个电子表格,我希望将其拆分为每个部门的单独电子表格,然后显示更多部门,我希望每个部门的.xls文件都以部门名称保存
部门字段是D列。
即。我想为每个文件提供一个.xls文件,只有部门1,部门2等的记录。
很遗憾,我无法发布电子表格的屏幕截图,因为我的代表还不够好。
我会用什么VBA代码来执行此操作?
答案 0 :(得分: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
这将在与您运行此工作簿的工作簿相同的文件夹中生成一个单独的工作簿,或者在您提供的路径中生成。