一、一次性拆分
1.打开目标excel,按alt + f11键打开VBE窗口
image2、在打开的窗口中输入以下代码:
Sub splitfile()
Dim arr, d As Object, k, t, i&, lc%, rng As Range, c%
c = Application.InputBox("请输入拆分列号", , 4, , , , , 1)
If c = 0 Then Exit Sub
Application.ScreenUpdating = False
Application.DisplayAlerts = False
arr = [a1].CurrentRegion
lc = UBound(arr, 2)
Set rng = [a1].Resize(, lc)
Set d = CreateObject("scripting.dictionary")
For i = 2 To UBound(arr)
If Not d.Exists(arr(i, c)) Then
Set d(arr(i, c)) = Cells(i, 1).Resize(1, lc)
Else
Set d(arr(i, c)) = Union(d(arr(i, c)), Cells(i, 1).Resize(1, lc))
End If
Next
k = d.Keys
t = d.Items
For i = 0 To d.Count - 1
With Workbooks.Add(xlWBATWorksheet)
rng.Copy .Sheets(1).[a1]
t(i).Copy .Sheets(1).[a2]
.SaveAs Filename:=ThisWorkbook.Path & "\" & k(i) & ".xls"
.Close
End With
Next
Application.DisplayAlerts = True
Application.ScreenUpdating = True
MsgBox "完毕"
End Sub
如下图所示:
image3、点击运行,如下图所示:
image4、然后输入按照某一列拆分的数字,列号是从1开始,如下图所示:
image5、点击确定即可,拆分完毕后就会有提示框,如下图所示:
image6、此时在源文件目录中就会生成对应的文件,如下图所示:
image以上是每次拆分都要执行,而如果是想让上边的代码保存到excel中,那么就需要以下步骤:
二、重复拆分
1.打开目标excel,按alt + f11键打开VBE窗口
image2.选择插入->模块粘贴下面代码到编辑器中
image代码:
Sub splitfile()
Dim arr, d As Object, k, t, i&, lc%, rng As Range, c%
c = Application.InputBox("请输入拆分列号", , 4, , , , , 1)
If c = 0 Then Exit Sub
Application.ScreenUpdating = False
Application.DisplayAlerts = False
arr = [a1].CurrentRegion
lc = UBound(arr, 2)
Set rng = [a1].Resize(, lc)
Set d = CreateObject("scripting.dictionary")
For i = 2 To UBound(arr)
If Not d.Exists(arr(i, c)) Then
Set d(arr(i, c)) = Cells(i, 1).Resize(1, lc)
Else
Set d(arr(i, c)) = Union(d(arr(i, c)), Cells(i, 1).Resize(1, lc))
End If
Next
k = d.Keys
t = d.Items
For i = 0 To d.Count - 1
With Workbooks.Add(xlWBATWorksheet)
rng.Copy .Sheets(1).[a1]
t(i).Copy .Sheets(1).[a2]
.SaveAs Filename:=ThisWorkbook.Path & "\" & k(i) & ".xls"
.Close
End With
Next
Application.DisplayAlerts = True
Application.ScreenUpdating = True
MsgBox "完毕"
End Sub
如下图所示:
image3、最后将该模块保存,此时会弹出如下对话框,如下图所示:
image4、选择是即可
5、然后回到excel界面,点击文件,然后选择选项,如下图所示:
image image6、然后选择自定义功能区->开发工具选择上,如下图所示:
image7、然后选择开发工具->插入->按钮,如下图所示:
image8、然后在弹出的框中选择刚刚保存的模块,如下图所示:
image9、此时会多出一个按钮,然后点击按钮即可运行模块,如下图所示:
image10、运行之后输入要按那一列进行拆分,如下图所示:
image11、点击确定之后即可开始分隔。
12、然后保存文件,之后每次打开文件都会有一个按钮,如下图所示:
image13、因此该文件就不用每次都复制代码了。
网友评论