[英]excel vba merge multiple sheets from multiple workbooks into one workbook
[英]Merge sheets from multiple workbooks into one sheet
我有很多擅長使用不同的工作表和相同的格式。 有沒有可用的插件將所有工作表合並到目標文件中的“合並”工作表中?
但是以下代碼無法合並為1張紙
Sub GopFileExcel()
Dim FilesToOpen
Dim x As Integer
On Error GoTo ErrHandler
Application.ScreenUpdating = False
FilesToOpen = Application.GetOpenFilename _
(FileFilter:="hMicrosoft Excel Files (*.xlsx), *.xlsx",
MultiSelect:=True, Title:="Files to Merg")
If TypeName(FilesToOpen) = “Boolean” Then
MsgBox "No Files were selected"
GoTo ExitHandler
End If
x = 1
While x <= UBound(FilesToOpen)
Workbooks.Open Filename:=FilesToOpen(x)
Sheets().Move After:=ThisWorkbook.Sheets(ThisWorkbook.Sheets.Count)
x = x + 1
Wend
ExitHandler:
Application.ScreenUpdating = True
Exit Sub
ErrHandler:
MsgBox Err.Description
Resume ExitHandler
End Sub
首先要做的是將所有工作表都放入一個工作簿中。 這是一些可以幫助您解決問題的代碼。
Sub GetSheets()
Path = "C:\Users\USERNAME\Downloads\Test\" 'File path will all your separate files
Filename = Dir(Path & "*.xls")
Do While Filename <> ""
Workbooks.Open Filename:=Path & Filename, ReadOnly:=True
For Each Sheet In ActiveWorkbook.Sheets
Sheet.Copy After:=ThisWorkbook.Sheets(1)
Next Sheet
Workbooks(Filename).Close
Filename = Dir()
Loop
End Sub
然后,您可以編寫一個循環以遍歷所有工作表並將數據移動到一個工作表中。
在@ Chrismas007答案之后,將所有工作表都放在一本工作簿中之后,可以使用下面的代碼片段將所需范圍復制到所需的目標工作表中。 這會將您復制的部分追加到目標表中的下一個未使用的列。
Dim ws As Worksheets
Dim lastcol As Integer
For Each ws In Worksheets
ThisWorkbook.Worksheets(ws).Column(copyrange).Copy
lastcol = Worksheets(targetsheet).Cells(1, Columns.Count).End(xlToLeft).Column + 1
ThisWorkbook.Worksheets(targetsheet).Cells(1, lastcol).PasteSpecial
Paste:=xlPasteValues, operation:=xlNone
Next
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.