将excel工作表按列拆分成多个excel文件小工具
时间: 2023-05-09 14:03:02 浏览: 656
将Excel工作表按列拆分成多个Excel文件是一项实用的任务,特别是在处理大量数据时。这里介绍一种小工具来轻松完成这个任务。
首先,需要使用VBA编写宏(Macro)来实现按列拆分Excel工作表。代码如下:
```
Sub SplitColumnsToFiles()
Dim path As String
Dim book As Workbook
Dim sheet As Worksheet
Dim col As Range
Dim lastRow As Long
Dim lastCol As Long
Dim fileName As String
path = Application.ActiveWorkbook.Path & "\"
Set book = Application.ActiveWorkbook
Set sheet = ActiveSheet
lastCol = sheet.Cells(1, Columns.Count).End(xlToLeft).Column
For Each col In sheet.Rows(1).Cells
If col.Column <= lastCol Then
fileName = path & col.Value & ".xlsx"
Set newBook = Workbooks.Add
With newBook
.Sheets(1).Cells(1, 1).Value = "This is " & col.Value & " column."
lastRow = sheet.Cells(Rows.Count, col.Column).End(xlUp).Row
sheet.Range(sheet.Cells(1, col.Column), sheet.Cells(lastRow, col.Column)).Copy .Sheets(1).Cells(2, 1)
.SaveAs fileName
.Close
End With
End If
Next col
End Sub
```
运行此宏后,Excel将按照每个列的标题进行拆分,并将每个文件命名为该列的标题。每个文件中包含两行数据:第一行是该列的标题,第二行是该列的数据。
使用此小工具,您可以轻松将一个大的Excel工作表拆分成多个Excel文件。同时,您还可以基于此代码进行调整,以实现您个人的需求。
阅读全文