Link to home
Start Free TrialLog in
Avatar of Billa7
Billa7

asked on

Delete unwanted sheets while copy the Workbook.

Hi Experts,

The attached macro able to copy and paste the workbook (attached) in a different location by removing “Data” sheet, other sheets are remained. Is that possible to revise the macro to delete all the sheets except “Data sheet”. The “Data” sheet should only consist Column A:C data and delete other object,  e.g. pictures. Hope Experts could help.



Sub exportWorkbook()
Dim fName As String
Dim wkb As Workbook
Dim wks As Worksheet
Dim mySht As Worksheet
Dim mySheets() As String
Dim i As Long
Dim newWkb As Workbook

    Application.DisplayAlerts = False
    Application.ScreenUpdating = False
    
    Set wkb = ThisWorkbook
    Set wks = wkb.Sheets("Data")
    
    fName = "D:\File Recovery\" & wks.Range("A1").Value & wks.Range("C4").Value & ".xls"
    'fName = ThisWorkbook.Path & "\" & wks.Range("A3").Value & wks.Range("C3").Value & ".xls"
    
    For Each mySht In ThisWorkbook.Worksheets
        If mySht.Name <> "Data" Then
            ReDim Preserve mySheets(i) As String
            mySheets(i) = mySht.Name
            i = i + 1
        End If
    Next mySht
    
    ReDim Preserve mySheets(UBound(mySheets) - 1)
    
    ThisWorkbook.Sheets(mySheets).Copy
    'Call RemoveAllMacros(ActiveWorkbook) 'in case there are macros in the sheet's codepages
    ActiveWorkbook.SaveAs Filename:=fName, FileFormat:=xlExcel8
    ActiveWorkbook.Close
    
    MsgBox "Successful export of " & fName
    Application.DisplayAlerts = False
    Application.ScreenUpdating = True
End Sub

Open in new window

Export-Sheet.xls
Avatar of StephenJR
StephenJR
Flag of United Kingdom of Great Britain and Northern Ireland image

If you use Move in line 29 instead of Copy, you won't need to delete them from the original. And for the other bit, try this:
With Sheets("Data")
        .UsedRange.Offset(, 3).Clear
        .DrawingObjects.Delete
    End With

Open in new window

Avatar of Billa7
Billa7

ASKER

Hi Stephen JR,

I have tried by modifying this line "ThisWorkbook.Sheets(mySheets).Move". However,I'm still getting the same result ("Data" has been deleted and other sheets "week 1 to week 5" are still exist). Meantime, I'm not very sure where to add the "other bit" line in my original code. Please assist.

ASKER CERTIFIED SOLUTION
Avatar of StephenJR
StephenJR
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Billa7

ASKER

Hi StephenJR,

Thanks a lot for the help.