我是靠谱客的博主 虚幻抽屉,这篇文章主要介绍VBA自学应用(3)——文件拆分,现在分享给大家,希望可以做个参考。

平时我们工作中会遇到要将一个工作表的数据拆分成若干个工作簿的要求。我辈中人当然是一个个“复制粘贴”啦,那么该如何将类似下图的数据按照要求拆分成工作簿呢?
在这里插入图片描述
要求:

  • 1、数据只有2018年的数据,以下单时间为准;
  • 2、一个客户一个文件,以客户代码为准;
  • 3、要求保存为:客户代码-客户名称.xlsx。
    代码如下
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
Sub 拆分表格() '客户代码 9 '客户名称 10 Application.ScreenUpdating = False t = Timer Dim arr Dim d As Object, con As Object, rst As Object Dim sql As String, str_cnn As String, strpath As String Dim hebing As String, strs As String, lujing As String Dim i As Long, j As Integer '------选择保存路径---- With Application.FileDialog(msoFileDialogFolderPicker) .AllowMultiSelect = False .InitialFileName = "D:" .Title = "请选择保存路径" .Show If .SelectedItems.Count > 0 Then strs = .SelectedItems(1) End If End With Dim wb As Workbook Set con = CreateObject("adodb.connection") Set d = CreateObject("scripting.dictionary") '链接EXCEL表格 strpath = ThisWorkbook.FullName If Application.Version < 12 Then str_cnn = "Provider=Microsoft.jet.OLEDB.4.0;Extended Properties='Excel 8.0;HDR=Yes;IMEX=';Data Source=" & strpath Else str_cnn = "Provider=Microsoft.ACE.OLEDB.12.0;Extended Properties=Excel 12.0;Data Source=" & strpath End If con.Open str_cnn '打开链接 arr = Range("a1:m" & Cells(Rows.Count, 1).End(3).Row) '-------提取数据---- For i = 3 To UBound(arr, 1) hebing = arr(i, 9) & arr(i, 10) '合并字段作为工作簿名称 If Not d.exists(hebing) Then d(hebing) = "" sql = "select * from [Sheet1$a1:m] where 客户代码&客户名称" & "='" & hebing & "'" Set rst = con.Execute(sql) Set wb = Workbooks.Add For j = 0 To rst.Fields.Count - 1 Cells(1, j + 1) = rst.Fields(j).Name Next wb.Worksheets(1).Range("a2").CopyFromRecordset rst Cells.EntireColumn.AutoFit lujing = strs & "" & hebing & ".xlsx" wb.SaveAs lujing wb.Close End If Next MsgBox "拆分成功!耗时:" & Format(Timer - t, "00:00:00") Application.ScreenUpdating = False End Sub

最后

以上就是虚幻抽屉最近收集整理的关于VBA自学应用(3)——文件拆分的全部内容,更多相关VBA自学应用(3)——文件拆分内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(107)

评论列表共有 0 条评论

立即
投稿
返回
顶部