我在一个文件夹中有20个Excel文件。我想将所有文件中的一个工作表合并为一个工作表。
列的顺序不相同,因此首先应查找列标题,然后复制粘贴该列中的数据。
在每个文件有多个工作表。我需要合并只有“管道”工作表。
Sub Test()
Dim FileFold As String
Dim FileSpec As String
Dim FileName As String
Dim ShtCnt As Long
Dim RowCnt As Long
Dim Merged As Workbook
Dim wb As Workbook
Dim ws As Worksheet
Dim Lastcol As Long
Dim i As Integer
Dim j As Integer
FileFold = "C:\Users\KK\Desktop\VR"
FileSpec = FileFold & Application.PathSeparator & "*.xlsx*"
FileName = Dir(FileSpec)
'Exit if no files found
If FileName = vbNullString Then
MsgBox Prompt:="No files were found that match " & FileSpec, Buttons:=vbCritical, Title:="Error"
Exit Sub
End If
With Application
.DisplayAlerts = False
.ScreenUpdating = False
End With
ShtCnt = 0
RowCnt = 1
Set Merged = Workbooks.Add
Do While FileName <> vbNullString
ShtCnt = ShtCnt + 1
Set wb = Workbooks.Open(FileName:=FileFold & Application.PathSeparator & FileName, UpdateLinks:=False)
Set ws = wb.Worksheets("PIPES")
With ws
LastColumn = ws.Cells.SpecialCells(xlCellTypeLastCell).Column
If .FilterMode Then .ShowAllData
If ws.Range(1, i).Value = Merged.Worksheets(1).Range(1, j) Then
.Range("A2").CurrentRegion.Copy Destination:=Merged.Worksheets(1).Cells(RowCnt, 1)
End If
End With
wb.Close SaveChanges:=False
RowCnt = Application.WorksheetFunction.CountA(Merged.Worksheets(1).Columns("A:A")) + 1
FileName = Dir
Loop
With Application
.DisplayAlerts = True
.ScreenUpdating = True
End With
MsgBox Prompt:="Finished merging.", Buttons:=vbInformation, Title:="Success"
End Sub
1条答案
按热度按时间b1uwtaje1#
编辑:测试和为我工作(做了几个修复)-