|
[广告] VBA代码宝 - VBA编程加强工具 · VBA代码随查随用 · 内置多项VBA编程加强工具 ★ 免费下载 ★ ★ 使用手册★
本帖最后由 opel-wong 于 2021-6-9 15:10 编辑
代码如下,供参考:
- Sub 条件拆分()
- Dim T1 As Date: T1 = Timer
- Dim arr, i As Long, bm As String, mFile As String, mPath As String
- Dim Rng As Range, sht As Worksheet, Key
- Dim d As Object: Set d = CreateObject("Scripting.Dictionary")
- For Each sht In Worksheets
- arr = sht.UsedRange.Value
- For i = 4 To UBound(arr)
- bm = arr(i, 5)
- If Len(bm) > 0 And InStr(bm, "部门") = 0 And Not d.Exists(bm) Then d(bm) = Empty
- Next
- Next
- Application.ScreenUpdating = False
- mPath = ThisWorkbook.Path & "\生成报表\" ' 报表生成路径,可自行修改
- If Dir(mPath, vbDirectory) = "" Then MkDir mPath ' 若文件夹不存在,则建立
- For Each Key In d.keys
- Worksheets.Copy
- For Each sht In Worksheets
- With sht
- arr = .UsedRange.Value
- For i = 4 To UBound(arr)
- bm = arr(i, 5)
- If Len(bm) > 0 And InStr(bm, "部门") = 0 And bm <> Key Then
- If Rng Is Nothing Then Set Rng = .Rows(i) Else Set Rng = Application.Union(Rng, .Rows(i))
- End If
- Next
- End With
- If Not Rng Is Nothing Then Rng.Delete: Set Rng = Nothing
- Next
- mFile = mPath & Key & ".xlsx"
- If Dir(mFile, vbHidden + vbNormal) <> "" Then Kill mFile ' 若同名文件存在,则删除
- ActiveWorkbook.SaveAs mFile, xlOpenXMLWorkbook ' 另存
- ActiveWorkbook.Close ' 关闭
- Next
- Application.ScreenUpdating = True
- MsgBox "表格已按部门拆分完成,用时约:" & Format(Timer - T1, "0.0" & " 秒!"), 64 + 0, "温馨提醒"
- End Sub
复制代码
|
|