Advertisement
Guest User

Untitled

a guest
May 26th, 2015
289
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.72 KB | None | 0 0
  1. Option Explicit
  2. Sub SHRINK_EXCEL_FILE_SIZE()
  3.  
  4. Dim WSheet As Worksheet
  5. Dim CSheet As String 'New Worksheet
  6. Dim OSheet As String 'Old WorkSheet
  7. Dim Col As Long
  8. Dim ECol As Long 'Last Column
  9. Dim lRow As Long
  10. Dim BRow As Long 'Last Row
  11. Dim Pic As Object
  12.  
  13. For Each WSheet In Worksheets
  14. WSheet.Activate
  15. 'Put the sheets in a variable to make it easy to go back and forth
  16. CSheet = WSheet.Name
  17. 'Rename the sheet to its name with _Delete at the end
  18. OSheet = CSheet & "_Delete"
  19. WSheet.Name = OSheet
  20. 'Add a new sheet and call it the original sheets name
  21. Sheets.Add
  22. ActiveSheet.Name = CSheet
  23. Sheets(OSheet).Activate
  24. 'Find the bottom cell of data on each column and find the further row
  25. For Col = 1 To Columns.Count 'Find the actual last bottom row
  26. If Cells(Rows.Count, Col).End(xlUp).Row > BRow Then
  27. BRow = Cells(Rows.Count, Col).End(xlUp).Row
  28. End If
  29. Next
  30.  
  31. 'Find the end cell of data on each row that has data and find the furthest one
  32. For lRow = 1 To BRow 'Find the actual last right column
  33. If Cells(lRow, Columns.Count).End(xlToLeft).Column > ECol Then
  34. ECol = Cells(lRow, Columns.Count).End(xlToLeft).Column
  35. End If
  36. Next
  37.  
  38. 'Copy the REAL set of data
  39. Range(Cells(1, 1), Cells(BRow, ECol)).Copy
  40. Sheets(CSheet).Activate
  41. 'Paste Every Thing
  42. Range("A1").PasteSpecial xlPasteAll
  43. 'Paste Column Widths
  44. Range("A1").PasteSpecial xlPasteColumnWidths
  45.  
  46. Sheets(OSheet).Activate
  47. For Each Pic In ActiveSheet.Pictures
  48. Pic.Copy
  49. Sheets(CSheet).Paste
  50. Sheets(CSheet).Pictures(Pic.Index).Top = Pic.Top
  51. Sheets(CSheet).Pictures(Pic.Index).Left = Pic.Left
  52. Next Pic
  53. Sheets(CSheet).Activate
  54.  
  55. 'Reset the variable for the next sheet
  56. BRow = 0
  57. ECol = 0
  58. Next WSheet
  59.  
  60. ' Since, Excel will automatically replace the sheet references for you on your formulas,
  61. ' the below part puts them back.
  62. ' This is done with a simple replace, replacing _Delete with nothing
  63. For Each WSheet In Worksheets
  64. WSheet.Activate
  65. Cells.Replace "_Delete", ""
  66. Next WSheet
  67.  
  68. 'Roll through the sheets and delete the original fat sheets
  69. For Each WSheet In Worksheets
  70. If Not Len(Replace(WSheet.Name, "_Delete", "")) = Len(WSheet.Name) Then
  71. Application.DisplayAlerts = False
  72. WSheet.Delete
  73. Application.DisplayAlerts = True
  74. End If
  75. Next
  76. End Sub
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement