概述
平时我们工作中会遇到要将一个工作表的数据拆分成若干个工作簿的要求。我辈中人当然是一个个“复制粘贴”啦,那么该如何将类似下图的数据按照要求拆分成工作簿呢?
要求:
- 1、数据只有2018年的数据,以下单时间为准;
- 2、一个客户一个文件,以客户代码为准;
- 3、要求保存为:客户代码-客户名称.xlsx。
代码如下
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)——文件拆分所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复