700字范文,内容丰富有趣,生活中的好帮手!
700字范文 > Excel中快速合并一个文件夹下多个工作簿中的所有工作表VBA代码

Excel中快速合并一个文件夹下多个工作簿中的所有工作表VBA代码

时间:2020-03-25 10:29:29

相关推荐

Excel中快速合并一个文件夹下多个工作簿中的所有工作表VBA代码

插入—模块 复制如下代码

Dim x As Integer "定义个一公有变量记录复制行数

"复制多个Excel文件中的内容到一个里

Sub combine()

x = 1

Dim folder As String

Dim count As Integer

folder = ChooseFolder()

"count = combineFiles(folder, "xls")

count = count + combineFiles(folder, "xlsx")

MsgBox (" succeed ")

End Sub

Function combineFiles(folder, appendix)

Dim MyFile As String

Dim s As String

Dim count, n, copiedlines As Integer

MyFile = Dir(folder & "\*." & appendix)

count = count + 1

n = 2

Do While MyFile <> ""

copiedlines = CopyFile(folder & "\" & MyFile, 2, n)

If copiedlines > 0 Then

n = n + copiedlines

count = count + 1

End If

MyFile = Dir

Loop

combineFiles = count

End Function

"复制数据

Function CopyFile(filename, srcStartLine, dstStartLine)

Dim book As Workbook

Dim sheet As Worksheet

Dim rc As Integer

CopyFile = 0

If filename = (ThisWorkbook.Path & "\" & ThisWorkbook.Name) Then

Exit Function

End If

Set book = Workbooks.Open(filename)

ThisWorkbook.Activate

For j = 1 To book.Sheets.count

book.Sheets(j).UsedRange.Copy Cells(x, 1)

With ActiveSheet.Cells.Find("*", Cells(1, 1), -4163, 1, 1, 2).MergeArea "通用判断最后一行

Rows(.Row + .Rows.count - 1).Select

x = Selection.Row + Selection.Rows.count - 1

End With

x = x + 1

Next j

book.Close

End Function

"选择文件夹

Function ChooseFolder() As String

Dim dlgOpen As FileDialog

Set dlgOpen = Application.FileDialog(msoFileDialogFolderPicker)

With dlgOpen

If .Show = -1 Then

ChooseFolder = .SelectedItems(1)

End If

End With

Set dlgOpen = Nothing

End Function

点击下方了解更多看视频解析

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。