Click here to Skip to main content
15,886,055 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
VBA beginner here !

I have a folder with many excel workbooks.
Consider folder as "C:\test" with workbooks named one.xlsx , two.xlsx , three.xlsx.
Each workbook has multiple sheets.
I need a macro to save only one sheet which is present in all workbooks to as a new excel sheet.

e.g I need to save "Demo" sheet present in all three excels as individual sheets.

Please help !
Posted
Comments
Maciej Los 2-Mar-14 13:21pm    
What have you tried till now?

1 solution

Here is an example:
VB
Option Explicit

Sub CopyDemoSheet()
Dim sPath As String, sFile As String
Dim dstWbk As Workbook, srcWbk As Workbook
Dim dstWsh As Worksheet, srcWsh As Worksheet

On Error GoTo Err_CopyDemoSheet

'create new workbook
Set dstWbk = Application.Workbooks.Add

'loop through the collection of Excel files
sPath = "C:\test\"
sFile = Dir(sPath)
Do While sFile <> ""
    'is this Excel file?
    If LCase(Right(sFile, 3)) <> "xls" Then GoTo SkipNext
    'open existing  Excel file
    Set srcWbk = Application.Workbooks.Open(sPath & "\" & sFile)
    'get source worksheet
    Set srcWsh = srcWbk.Worksheets("Demo")
    'copy source workshhet to destination file - at the end ;)
    srcWsh.Copy dstWbk.Worksheets(dstWbk.Worksheets.Count)
    'get destination worksheet
    Set dstWsh = dstWbk.Worksheets(dstWbk.Worksheets.Count)
    'you can proccess with destination Worksheet
    'for example, you can change the name of it
    'dstwsh.Name = "Whatever"
    
    'close
    srcWbk.Close SaveChanges:=False

'if it's not an Excel file
SkipNext:
    'get next file
    sFile = Dir()
Loop

'exit procedure
Exit_CopyDemoSheet:
    'ignore errors and clean up ;)
    On Error Resume Next
    'close destination file
    'dstWbk.Close SaveChanges:=True
    Set dstWbk = Nothing
    Set dstWsh = Nothing
    Set srcWbk = Nothing
    Set srcWsh = Nothing
    Exit Sub
    
Err_CopyDemoSheet:
    'display error message
    MsgBox Err.Description, vbExclamation, "Error no.:" & Err.Number
    'go to exit procedure
    Resume Exit_CopyDemoSheet
End Sub


Please, read all comments.

Note: not tested!
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900