I'm working on a spreadsheet and need to write a macro that at the end of the day will summarize all the other sheets. I want the summary sheet to refresh each day and I also want the sheet to be linked to a pivot table that will refresh off of the new summary sheet data.
This is what I have so far. It summarizes all the sheets into one sheet, but creates a new summary sheet each day instead of just refreshing the sheet like I want.
Option Explicit
Sub Merge_Sheets()
' Takes every sheet in a workbook and pastes everything into
' one sheet (only copies headings once)
Dim mergedSheet As String 'Hold the name of the new sheet created
' Insert a new worksheet at the beginning of the workbook
ActiveWorkbook.Worksheets.Add Before:=Worksheets(1)
Dim sameNameCount As Integer
sameNameCount = 2
Do
If Not WorksheetExists("Summary") Then
ActiveSheet.Name = "Summary"
Exit Do
ElseIf Not WorksheetExists("Summary " & sameNameCount) Then
ActiveSheet.Name = "Summary " & sameNameCount
Exit Do
Else
sameNameCount = sameNameCount + 1
End If
Loop
mergedSheet = ActiveSheet.Name
' Loop through each sheet, copying each
Dim wksht As Worksheet
For Each wksht In ActiveWorkbook.Worksheets
If Left(wksht.Name, Len("Summary")) = "Summary" Then
GoTo nextWksht
End If
wksht.Activate
If Worksheets(mergedSheet).Cells(1, 1) = "" Then
' Fill in headings
Range("A1:I1").Select
Application.CutCopyMode = False
Selection.Copy
Sheets(mergedSheet).Activate
Cells(1, 1).Select
ActiveSheet.Paste
End If
wksht.Activate
Range("A2:I" & wksht.UsedRange.Rows.Count).Select
Application.CutCopyMode = False
Selection.Copy
Sheets(mergedSheet).Activate
Range("A" & getNextEmptyRowInSheet(ActiveSheet, 2)).Select
ActiveSheet.Paste
nextWksht:
Next
End Sub
Public Function WorksheetExists(WorkSheetName As String, Optional WorkBookName As String)
Dim WS As Worksheet
On Error Resume Next
If WorkBookName = vbNullString Then
Set WS = Sheets(WorkSheetName)
Else
Set WS = Workbooks(WorkBookName).Sheets(WorkSheetName)
End If
On Error GoTo 0
WorksheetExists = Not WS Is Nothing
End Function
Function getNextEmptyRowInSheet(sheet As Worksheet, testColumn As Integer) As Integer
Dim row As Integer
row = 1
sheet.Activate
Do
If Cells(row, testColumn).Value = "" Then
getNextEmptyRowInSheet = row
Exit Function
Else
row = row + 1
End If
Loop
End Function
Thanks for the help!!!
-Christina
Bookmarks