VBA - Excel: How can I optimize this code? - excel

For a long time I'm not playing with VBA, so we have a spreadsheet on my work and checkng its code, I'm sure it can be improved.
Basically this spreadsheet has literally 200 buttons (100 to open and another 100 to close) and it copies the data from one sheet to another. Below are the examples of two of this macros.
Macro #1:
Sub IT100stop()
'
' newstop Macro
'
' Keyboard Shortcut: Ctrl+s
'
Application.ScreenUpdating = False
Range("G47").Select
ActiveCell.FormulaR1C1 = "DOWN"
Range("H47").Select
ActiveCell.FormulaR1C1 = _
"=YEAR(TODAY())&MONTH(TODAY())&DAY(TODAY())&HOUR(NOW())&MINUTE(NOW())&SECOND(NOW())"
Range("H47").Select
Selection.Copy
Selection.PasteSpecial Paste:=xlPasteValuesAndNumberFormats, Operation:= _
xlNone, SkipBlanks:=False, Transpose:=False
Range("j47").Select
Application.CutCopyMode = False
ActiveCell.FormulaR1C1 = "=NOW()"
Range("j47").Select
Selection.Copy
Selection.PasteSpecial Paste:=xlPasteValuesAndNumberFormats, Operation:= _
xlNone, SkipBlanks:=False, Transpose:=False
Range("K47").Select
Application.CutCopyMode = False
Application.CutCopyMode = False
ActiveCell.FormulaR1C1 = "=IF(RC[-1]="""","""",IF(NOW()-RC[-1]<1,HOUR(NOW()-RC[-1])&"" h ""&MINUTE(NOW()-RC[-1])&"" m"",IF(DAYS(NOW(),RC[-1])<2,DAYS(NOW(),RC[-1])&"" day"",DAYS(NOW(),RC[-1])&"" days"")))"
Range("F47").Select
Application.ScreenUpdating = True
End Sub
Macro #2:
Sub IT100released()
'
' newreleased Macro
'
' Keyboard Shortcut: Ctrl+r
'
Application.ScreenUpdating = False
Sheets("Database").Select
Range("A2").Select
Application.CutCopyMode = False
Rows("2:2").Select
Selection.Insert shift:=xlDown, CopyOrigin:=xlFormatFromLeftOrAbove
Sheets("SINOPTIC").Select
Range("F47:U47").Select
Selection.Copy
Sheets("Database").Select
Range("A2").Select
Selection.PasteSpecial Paste:=xlPasteValuesAndNumberFormats, Operation:= _
xlNone, SkipBlanks:=False, Transpose:=False
Sheets("SINOPTIC").Select
Range("G47").Select
ActiveCell.FormulaR1C1 = "OK"
Range("H47:U47").Select
Selection.ClearContents
Application.ScreenUpdating = True
End Sub
The question is: what can we do to improve this code? If I add this following code before and after the actual macro code, will the calculations be faster?
Application.Calculation = xlCalculationManual
Application.ScreenUpdating = False
Application.DisplayStatusBar = False
Application.EnableEvents = False
'Macro Code
Application.EnableEvents = True
Application. DisplayStatusBar = True
Application.ScreenUpdating = True
Application.Calculation = xlCalculationAutomatic
Thanks a lot!

Pay attention to what BigBen wrote: avoid the Select; that is the code created by the macro recorder, but it performs many unnecessary operations.
This is the "human" version of your macro # 2
Sub IT100released()
'
' newreleased Macro
'
' Keyboard Shortcut: Ctrl+r
'
With Application
.Calculation = xlCalculationManual
.ScreenUpdating = False
.EnableEvents = False
Sheets("Database").Rows("2:2").Insert shift:=xlDown, CopyOrigin:=xlFormatFromLeftOrAbove
Sheets("SINOPTIC").Range("F47:U47").Copy
Sheets("Database").Range("A2").PasteSpecial Paste:=xlPasteValuesAndNumberFormats
Sheets("SINOPTIC").Range("G47") = "OK"
Sheets("SINOPTIC").Range("H47:U47").ClearContents
.EnableEvents = True
.ScreenUpdating = True
.Calculation = xlCalculationAutomatic
End With
End Sub

Related

Correct VBA run time issue

I have created a simple macro to cut and paste data from one sheet to another and every once in a while I will get the Run time error 1004 cannot paste data error. It doesn't do it all the time.
Here is my current code:
Sub INSERTVE()
'
' INSERTVE Macro
'
' Keyboard Shortcut: Ctrl+Shift+I
'
Application.Calculation = xlCalculationManual
Application.ScreenUpdating = False
Application.DisplayStatusBar = False
ActiveSheet.DisplayPageBreaks = False
Application.ScreenUpdating = False
ActiveWorkbook.Names.Add Name:="newrowa", RefersToR1C1:=Rows(ActiveCell.Row)
Application.Goto Reference:="newrowa"
Application.Goto Reference:="NEWTRENDLOGITEM"
Selection.Copy
Application.Goto Reference:="newrowa"
Selection.EntireRow.Insert
Range("newrowa").Select
ActiveCell.Rows("1:1").EntireRow.Select
Application.Goto Reference:="insertsection"
Selection.Copy
Application.Goto Reference:="LASTROW"
Selection.EntireRow.Insert
ActiveWorkbook.Names.Add Name:="newrowZ", RefersToR1C1:=Rows(ActiveCell.Row)
Range("newrowZ").Select
ActiveWorkbook.Names("newrowZ").Delete
ActiveCell.Rows("1:1").EntireRow.Select
ActiveWorkbook.Names.Add Name:="newrowZ", RefersToR1C1:=Rows(ActiveCell.Row)
ActiveCell.Rows("1:1").EntireRow.Select
ActiveCell.Offset(0, 8).Range("A1").Select
Sheets("ve-01").Select
Application.Goto Reference:="newrowa"
ActiveCell.Rows("1:1").EntireRow.Select
ActiveCell.Offset(-1, 2).Range("A1").Select
Selection.Copy
Application.Goto Reference:="LASTROW"
ActiveCell.Offset(-13, 2).Range("A1").Select
**ActiveSheet.Paste link:=True**
Application.Goto Reference:="newrowa"
ActiveCell.Offset(-1, 3).Range("A1").Select
Selection.Copy
Application.Goto Reference:="LASTROW"
ActiveCell.Offset(-13, 3).Range("A1").Select
ActiveSheet.Paste link:=True
Application.Goto Reference:="LASTROW"
ActiveCell.Offset(-2, 16).Range("A1").Select
Selection.Copy
Application.Goto Reference:="newrowa"
ActiveCell.Rows("1:1").EntireRow.Select
ActiveCell.Offset(-1, 13).Range("A1").Select
ActiveSheet.Paste link:=True
Application.Goto Reference:="newrowa"
ActiveCell.Rows("1:1").EntireRow.Select
ActiveCell.Offset(-1, 1).Range("A1").Select
Selection.Copy
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Sheets("VE-01").Select
Range("newrowa").Select
ActiveWorkbook.Names("newrowa").Delete
ActiveWorkbook.Names("newrowz").Delete
Application.CutCopyMode = False
Application.ScreenUpdating = True
Application.DisplayStatusBar = True
ActiveSheet.DisplayPageBreaks = True
Application.Calculation = xlCalculationAutomatic
End Sub
Any suggestions or ideas on why it only does this once in a while? Any tips for a newbie on how to correct this? The code errors out when it gets to ActiveSheet.Paste link:=True
Thanks,

Unhide worksheet within a macro does not work when workbook is protected

I have an issue with unprotecting / protecting a sheet when I run a macro. I read a few posts stating that I should insert the ActiveSheet.Unprotect Password:="my password" bit before and then the ActiveSheet.Unprotect Password:="my password", into the macro, but this has not worked. Any suggestions would be gratefully appreciated.
ActiveSheet.Unprotect Password:="my password"
Sheets("sheet1").Select
Sheets("sheet2").Visible = True
Sheets("sheet2").Select
Cells.Select
Selection.Copy
Workbooks.Add
Cells.Select
ActiveSheet.Paste
Application.CutCopyMode = False
Selection.Copy
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, skipBlanks _
:=False, Transpose:=False
Application.CutCopyMode = False
Range("A1").Select
Application.DisplayAlerts = False
ActiveWorkbook.SaveAs Filename:="C:\file.csv" _
, FileFormat:=xlCSV, CreateBackup:=False
Application.DisplayAlerts = True
Application.DisplayAlerts = False
ActiveWorkbook.Save
Application.DisplayAlerts = True
Application.DisplayAlerts = False
ActiveWindow.Close
Application.DisplayAlerts = True
Sheets("Sheet2").Select
ActiveWindow.SelectedSheets.Visible = False
Sheets("sheet1").Select
ActiveSheet.Protect Password:="my password"

Why does VBA macro stop on active cell change?

I have been away for 7 years from writing VBA and today I have been asked to do a simple thing and it doesn't work
I am trying to take the contents of 52 weekly summaries and put them all into one sheet:
So I can go to the first sheet - copy the data I need - go to the summary sheet - paste the data - and then it stops ... same if I just change the value of a cell - it changes the value and then stops.
Am I missing a security setting or something?
Here is the VBA
Sub Macro3()
'
' Macro3 Macro
'
' Take cell contents of active sheet and paste into summary sheet
Sheets("we 03 Jan").Select
Do
shtName = ActiveSheet.Name
Range("A10:U39").Select
Application.CutCopyMode = False
Selection.Copy
Sheets("Full Year").Select
ActiveCell.Offset(1, 0).Range("A1").Select
ActiveCell.Value = shtName
' stops here
ActiveCell.Offset(1, 0).Range("A1").Select
Selection.PasteSpecial Paste:=xlValues, Operation:=xlNone, SkipBlanks:= _
False, Transpose:=False
' stops here if previous line causing stop is removed
Sheets(shtName).Select
If ActiveSheet.Index = Worksheets.Count Then
Worksheets(1).Select
Exit Sub
Else
ActiveSheet.Next.Select
End If
Loop
End Sub
Does this work?
Sub Macro3()
Dim n As Long
Dim ws As Worksheet
On Error GoTo clean_up
With Application
.ScreenUpdating = False
.EnableEvents = False
End With
Sheets("we 03 Jan").Select
For n = ActiveSheet.Index To Sheets.Count
Set ws = Sheets(n)
ws.Range("A10:U39").Copy
With Sheets("Full Year").Cells(Rows.Count, "A").End(xlUp).Offset(1)
.Value = ws.Name
.Offset(1, 0).PasteSpecial Paste:=xlValues, Operation:=xlNone, _
SkipBlanks:=False, Transpose:=False
End With
Next n
clean_up:
With Application
.EnableEvents = True
.ScreenUpdating = True
End With
End Sub

Excel macro crashes after running for a few minutes

My code runs for about 5min and the goes into recovery error/message. I have posted 3 Call macros but have 40 in the code.
During the macro the cells need to calculate and I tried a time delay to help but no good.
Private Sub Worksheet_calculate()
If Range("$be8").Value = 1 Then
Application.EnableEvents = True
Call Macro1
Application.EnableEvents = False
End If
If Range("$bf8").Value = 1 Then
Application.EnableEvents = True
Call Macro2
Application.EnableEvents = False
End If
If Range("$bg8").Value = 1 Then
Application.EnableEvents = True
Call Macro3
Application.EnableEvents = False
End If
Sub Macro1()
'
'
Macro1 Macro
'
'
Sheets("Calc. 1").Select
Rows("11:11").Select
Selection.Insert Shift:=xlDown, CopyOrigin:=xlFormatFromLeftOrAbove
Application.Wait (Now + TimeValue("0:00:05"))
Rows("7:7").Select
Selection.Copy
Rows("11:11").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Range("B1").Select
Application.CutCopyMode = False
ActiveCell.FormulaR1C1 = ""
Range("B2").Select
Sheets("Calc.").Select
Range("A7:Q50002").Select
Selection.Copy
Range("A3").Select
ActiveSheet.Paste
Calculate
Range("AZ3").Select
Selection.Copy
Range("BA3").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Range("A1").Select
Application.CutCopyMode = False
ActiveCell.FormulaR1C1 = ""
Range("B1").Select
Workbooks.Add
DoEvents
End Sub
Sub Macro2()
'
' Macro2 Macro
'
'
Sheets("Calc. 1").Select
Rows("11:11").Select
Selection.Insert Shift:=xlDown, CopyOrigin:=xlFormatFromLeftOrAbove
Application.Wait (Now + TimeValue("0:00:05"))
Rows("7:7").Select
Selection.Copy
Rows("11:11").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Range("B1").Select
Application.CutCopyMode = False
ActiveCell.FormulaR1C1 = ""
Range("B2").Select
Sheets("Calc.").Select
Range("A8:Q50002").Select
Selection.Copy
Range("A3").Select
ActiveSheet.Paste
Calculate
Range("AZ3").Select
Selection.Copy
Range("BA3").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Range("A1").Select
Application.CutCopyMode = False
ActiveCell.FormulaR1C1 = ""
Range("B1").Select
Workbooks.Add
DoEvents
End Sub
Sub Macro3()
'
' Macro3 Macro
'
'
Sheets("Calc. 1").Select
Rows("11:11").Select
Selection.Insert Shift:=xlDown, CopyOrigin:=xlFormatFromLeftOrAbove
Application.Wait (Now + TimeValue("0:00:05"))
Rows("7:7").Select
Selection.Copy
Rows("11:11").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Range("B1").Select
Application.CutCopyMode = False
ActiveCell.FormulaR1C1 = ""
Range("B2").Select
Sheets("Calc.").Select
Range("A9:Q50002").Select
Selection.Copy
Range("A3").Select
ActiveSheet.Paste
Calculate
Range("AZ3").Select
Selection.Copy
Range("BA3").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Range("A1").Select
Application.CutCopyMode = False
ActiveCell.FormulaR1C1 = ""
Range("B1").Select
Workbooks.Add
DoEvents
End Sub
First, this is just a big pack of recorded macros, and therefore nearly unreadable, as hinted by Matt Webb in its excellent comment. That being said, I went to do some analysis.
The macros are strictly the same, besides the column of the Range("A7:Q50002").Select, which varies from 7 to 9 (and probably up to 46, if you really have 40 of those). Time to make a proper sub with a parameter :
Private Sub Worksheet_calculate()
If Range("$be8").Value = 1 Then
Application.EnableEvents = True
Call Macro(myRow)
Application.EnableEvents = False
End If
If Range("$bf8").Value = 1 Then
Application.EnableEvents = True
Call Macro(myRow)
Application.EnableEvents = False
End If
If Range("$bg8").Value = 1 Then
Application.EnableEvents = True
Call Macro(myRow)
Application.EnableEvents = False
End If
End Sub
Sub Macro(myRow)
Sheets("Calc. 1").Rows("11:11").Insert Shift:=xlDown, CopyOrigin:=xlFormatFromLeftOrAbove
Application.Wait (Now + TimeValue("0:00:05"))
Rows("7:7").Copy
Rows("11:11").PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Range("B1").Select
Application.CutCopyMode = False
ActiveCell.FormulaR1C1 = ""
'Range("B2").Select
Sheets("Calc.").Range("A" & CStr(myRow) & ":Q50002").Copy
Range("A3").Select
ActiveSheet.Paste
Calculate
Range("AZ3").Copy
Range("BA3").PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Range("A1").Select
Application.CutCopyMode = False
ActiveCell.FormulaR1C1 = ""
'Range("B1").Select
Workbooks.Add
DoEvents
End Sub
it'still ugly, but now, you just have 1 main procedure instead of 40, and I cleaned a little bit. I also did comment the useless selects.
Next question : what does it do? Seems like it
inserts the row 11, then copies the row 7 into. That one shall not be problematic.
Copies a specific cell from another sheet to the current sheet. Well, why not.
Calculates. Here we have a problem. I have no clue of your calculations, and there very well might be circular things here, or insane amounts of calculations to do. Especially when I see hard-coded values going to the 50000th row... The wolf may hide here. Depends on your worksheet. This is my first suspect.
Copy another cell in the main sheet. No risk here.
Add an empty workbook. Without anything. Hum, are you sure? If your 40 values are positive, you dynamically open 40 workbooks, without naming them, or putting any data in them??? This is my second and last suspect.
Now, you have to troubleshoot yourself to know which suspect is guilty. For that, you can add breakpoints on a few strategic lines of the macro, to see what takes time(my bet on the calculate, but I may be wrong). Especially before & after the calculate & the Workbook.add
But ask yourself is everything I listed is useful, especially the calculate part, and especially the workbook.add part. Your macro might very well flood the computer memory with all those workbooks open in memory that are still useless.

Extract data from Excel workbook with specific procedure to report sheet

Here is the problem in my situation:
My workbook counts from the first of the month till the 15th. (sheet 1-15)
Sometimes it happens that there are 3 weeks-counts in half a month.
The weeks are counted from Monday till Sunday in de excell cels.
NOTE: I have hidden some rows and columns due to work with dates.
Now what I should establish with VB is a monthly report that shows me on how many jobs each employeé has done due to make a calculation of workspeed/ job.
All the jobs are variable and can be selected in each day of de workbook (see listed jobs sheets(1).thisworkbook.
It is possible that I have to give weekly evaluations, so it is nessecery that VB wil still use the same wbnew and expand the input of the daily workhours.
I already made a 'partial' code to start with but I can not handle to the rest.
The code should look for how many employees there are. (this I fill in in sheet(“1”) of workbook).
It should look in each workday sheet (“1”) –sheet(“15) for:
• Does the employee exist?
• Wat day of sheet we are
• Which jobs it has done (jobdescription + code job required in listing)
• If job already exist just fill in in the same row, but in the right Colum of date, if the job is not done, don't show the jobname, don't show the jobcode
• How many time spend on the job
• To control if the counting is correct you can see the total of hours in column (AA) in sheet (“15”) of workbook and cel (“S15”) of montly reportsheet
(in this case both have 15hours displayed = ok).
I have a workbook and a example of reportsheet posted.
In the workbook you will find also my attemt to start with a code (see remarks)
Hopefully someone can help me out.
dowloadlink Workbooks klick here first
here is my attemps but it is far from what I really need to do
Sub Macro1()
'
' Macro1 Macro
'
Dim wbNew As Workbook
'I need here VBA to look for if the file "per 1-15 exists and don't create a new file but just exand the data
'I need something like for each ws of thisworkbook
'also the rest of the required formula is too difficult for me
'Does the employee exist?
'Wat day of sheet we are
'Which jobs it has done (jobdescription + code job required in listing)
'If job already exist just fill in in the same row, but in the right Colum of date, if the job is not done, don't show the jobname, don't show the jobcode
'How many time spend on the job
'To control if the counting is correct you can see the total of hours in column (AA) in sheet (“15”) of workbook and cel (“S15”) of montly reportsheet (in this case both have 15hours displayed = ok).
'you can have a look at my example reportsheet
ThisWorkbook.Sheets(1).Activate
Range("A1:S53").Select
Range("S53").Activate
Selection.Copy
Set wbNew = Workbooks.Add
wbNew.Sheets(1).Activate
Range("A1:S53").Select
Selection.PasteSpecial Paste:=xlPasteColumnWidths, Operation:=xlNone, _
SkipBlanks:=False, Transpose:=False
wbNew.Sheets(1).Select
Selection.PasteSpecial Paste:=xlPasteColumnWidths, Operation:=xlNone, _
SkipBlanks:=False, Transpose:=False
Range("A1").Select
ActiveSheet.Paste
ThisWorkbook.Sheets(1).Activate
Range("C12").Select
Application.CutCopyMode = False
Selection.Copy
wbNew.Sheets(1).Activate
Range("C12").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
ThisWorkbook.Sheets("1").Activate
Sheets("1").Select
Range("B8").Select
Application.CutCopyMode = False
Selection.Copy
wbNew.Sheets(1).Activate
Range("M5").Select
wbNew.Sheets(1).Paste
Range("L7:Q7").Select
Selection.FormatConditions.Delete
Selection.FormatConditions.Add Type:=xlCellValue, Operator:=xlEqual, _
Formula1:="=$C$12"
Selection.FormatConditions(Selection.FormatConditions.Count).SetFirstPriority
Range("R7:S7").Select
Selection.Copy
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Application.CutCopyMode = False
Selection.NumberFormat = "0"
With Selection.FormatConditions(1).Font
.Bold = True
.Italic = False
.TintAndShade = 0
End With
With Selection.FormatConditions(1).Interior
.PatternColorIndex = xlAutomatic
.Color = 65535
.TintAndShade = 0
End With
Selection.FormatConditions(1).StopIfTrue = False
Range("A1:S53").Select
Application.CutCopyMode = False
ActiveSheet.PageSetup.PrintArea = "$A$1:$S$53"
Application.PrintCommunication = False
Application.PrintCommunication = True
ActiveSheet.PageSetup.PrintArea = "$A$1:$S$53"
Application.PrintCommunication = False
With ActiveSheet.PageSetup
.PrintHeadings = False
.PrintGridlines = False
.PrintComments = xlPrintNoComments
.PrintQuality = 600
.CenterHorizontally = False
.CenterVertically = False
.Orientation = xlPortrait
.Draft = False
.PaperSize = xlPaperA4
.FirstPageNumber = xlAutomatic
.Order = xlDownThenOver
.BlackAndWhite = False
.Zoom = False
.FitToPagesWide = 1
.FitToPagesTall = 1
.PrintErrors = xlPrintErrorsDisplayed
.OddAndEvenPagesHeaderFooter = False
.DifferentFirstPageHeaderFooter = False
.ScaleWithDocHeaderFooter = True
.AlignMarginsHeaderFooter = True
End With
Application.PrintCommunication = True
' I also should hide row 13 , but it gives strage vieuws at the moment
Sheets(1).Name = Range("M5").Value
Sheets.Add After:=ActiveSheet
ThisWorkbook.Sheets(1).Activate
Range("A1:S53").Select
Range("S53").Activate
Selection.Copy
wbNew.Sheets(2).Activate
Range("A1:S53").Select
Selection.PasteSpecial Paste:=xlPasteColumnWidths, Operation:=xlNone, _
SkipBlanks:=False, Transpose:=False
wbNew.Sheets(2).Select
Selection.PasteSpecial Paste:=xlPasteColumnWidths, Operation:=xlNone, _
SkipBlanks:=False, Transpose:=False
Range("A1").Select
ActiveSheet.Paste
ThisWorkbook.Sheets(1).Activate
Range("C12").Select
Application.CutCopyMode = False
Selection.Copy
wbNew.Sheets(1).Activate
Range("C12").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
ThisWorkbook.Sheets("1").Activate
Sheets("1").Select
Range("B9").Select
Application.CutCopyMode = False
Selection.Copy
wbNew.Sheets(2).Activate
Range("M5").Select
wbNew.Sheets(2).Paste
Range("L7:Q7").Select
Selection.FormatConditions.Delete
Selection.FormatConditions.Add Type:=xlCellValue, Operator:=xlEqual, _
Formula1:="=$C$12"
Selection.FormatConditions(Selection.FormatConditions.Count).SetFirstPriority
Range("R7:S7").Select
Selection.Copy
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Application.CutCopyMode = False
Selection.NumberFormat = "0"
With Selection.FormatConditions(1).Font
.Bold = True
.Italic = False
.TintAndShade = 0
End With
With Selection.FormatConditions(1).Interior
.PatternColorIndex = xlAutomatic
.Color = 65535
.TintAndShade = 0
End With
Selection.FormatConditions(1).StopIfTrue = False
Range("A1:S53").Select
Application.CutCopyMode = False
ActiveSheet.PageSetup.PrintArea = "$A$1:$S$53"
Application.PrintCommunication = False
Application.PrintCommunication = True
ActiveSheet.PageSetup.PrintArea = "$A$1:$S$53"
Application.PrintCommunication = False
With ActiveSheet.PageSetup
.PrintHeadings = False
.PrintGridlines = False
.PrintComments = xlPrintNoComments
.PrintQuality = 600
.CenterHorizontally = False
.CenterVertically = False
.Orientation = xlPortrait
.Draft = False
.PaperSize = xlPaperA4
.FirstPageNumber = xlAutomatic
.Order = xlDownThenOver
.BlackAndWhite = False
.Zoom = False
.FitToPagesWide = 1
.FitToPagesTall = 1
.PrintErrors = xlPrintErrorsDisplayed
.OddAndEvenPagesHeaderFooter = False
.DifferentFirstPageHeaderFooter = False
.ScaleWithDocHeaderFooter = True
.AlignMarginsHeaderFooter = True
End With
Application.PrintCommunication = True
' I also should hide row 13 , but it gives strage vieuws at the moment
Sheets(2).Name = Range("M5").Value
' instead of writing "per 1-15" down here, I should refer to Range("R7").Value, but it is not working
' in Cel R7 there is written "per 1-15" as value now(I believe)
ActiveWorkbook.SaveAs Filename:= _
"C:\Path\" & "per 1-15" & " " & Format(Range("C12"), "mmm") & ".xlsx"
FileFormat = xlOpenXMLWorkbook
Range("A15").Select
ActiveWindow.Close
End Sub
in order to start somewhere with a constructive way you can find a second attemt below
'in order to start with a creation of a new workbook I should do some handlings first
'I want to create a workbook where the names of the employees are shown , with in the sheetnames the names of the employees
'in thisworkbook.sheet "1" there is a list of 30 names listed Column B8:B37, that I shoud copy into a new workbook
Dim i As Long
Dim StartRow As Long
Dim LastRow As Long
Dim wbnew As Workbook
Dim wsNew As Worksheet
'STARTING FROM THIS WORKBOOK
'Set Start Row thisworkbook
StartRow = 8
'Set Last Row thisworkbook
LastRow = .Range("B" & .Rows.Count).End(xlUp).Row
For i = StartRow To LastRow
'copy the name into a cel "M5" of wbnew (see below)
If .Range("B" & i).Value <> "NAME" Then
' if cel is empty do nothing
If .Range("B" & i).Value <> "" Then
On Error Resume Next
'create new workbook
Set wbnew = Workbooks.Add
' launch here the sheet routine below
'wbnew sheet routine Handling---------------------------------------------------------
'when in this specific cells there is written "Name" , that Cell should not be copied to a new sheet wbnew
'when in cels B8:B37 there is written a name ,the code should make a new workbook (wbnew) with following procedures
'this selection is always a copy from this specific sheet
ThisWorkbook.Sheets(1).Activate
Range("A1:S53").Select
Range("S53").Activate
Selection.Copy
'here I need to write activate always the new sheet wbnew
wbnew.Sheets(2).Activate
Range("A1:S53").Select
Selection.PasteSpecial Paste:=xlPasteColumnWidths, Operation:=xlNone, _
SkipBlanks:=False, Transpose:=False
'here I need to write select always the new sheetwbnew
wbnew.Sheets(2).Select
Selection.PasteSpecial Paste:=xlPasteColumnWidths, Operation:=xlNone, _
SkipBlanks:=False, Transpose:=False
Range("A1").Select
ActiveSheet.Paste
' this has to stay like this
ThisWorkbook.Sheets(1).Activate
Range("C13").Select
Application.CutCopyMode = False
Selection.Copy
'here I need to write select always the new sheet wbnew
wbnew.Sheets(2).Activate
Range("C13").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
ThisWorkbook.Sheets("1").Activate
' this has to stay like this
Sheets("1").Select
Range("B9").Select
Application.CutCopyMode = False
Selection.Copy
'here I need to write activate always the new sheet wbnew
wbnew.Sheets(2).Activate
Range("M5").Select
wbnew.Sheets(2).Paste
Range("L7:Q7").Select
Selection.FormatConditions.delete
Selection.FormatConditions.Add Type:=xlCellValue, Operator:=xlEqual, _
Formula1:="=$C$13"
Selection.FormatConditions (Selection.FormatConditions.Count).SetFirstPriority
With Selection.FormatConditions(1).Font
.Bold = True
.Italic = False
.TintAndShade = 0
End With
With Selection.FormatConditions(1).Interior
.PatternColorIndex = xlAutomatic
.Color = 65535
.TintAndShade = 0
End With
Selection.FormatConditions(1).StopIfTrue = False
Range("A1:S53").Select
Application.CutCopyMode = False
ActiveSheet.PageSetup.PrintArea = "$A$1:$S$53"
Application.PrintCommunication = False
With ActiveSheet.PageSetup
.PrintTitleRows = ""
.PrintTitleColumns = ""
End With
Application.PrintCommunication = True
ActiveSheet.PageSetup.PrintArea = "$A$1:$S$53"
Application.PrintCommunication = False
With ActiveSheet.PageSetup
.LeftHeader = ""
.CenterHeader = ""
.RightHeader = ""
.LeftFooter = ""
.CenterFooter = ""
.RightFooter = ""
.LeftMargin = Application.InchesToPoints(0.708661417322835)
.RightMargin = Application.InchesToPoints(0.708661417322835)
.TopMargin = Application.InchesToPoints(0.748031496062992)
.BottomMargin = Application.InchesToPoints(0.748031496062992)
.HeaderMargin = Application.InchesToPoints(0.31496062992126)
.FooterMargin = Application.InchesToPoints(0.31496062992126)
.PrintHeadings = False
.PrintGridlines = False
.PrintComments = xlPrintNoComments
.PrintQuality = 600
.CenterHorizontally = False
.CenterVertically = False
.Orientation = xlPortrait
.Draft = False
.PaperSize = xlPaperA4
.FirstPageNumber = xlAutomatic
.Order = xlDownThenOver
.BlackAndWhite = False
.Zoom = False
.FitToPagesWide = 1
.FitToPagesTall = 1
.PrintErrors = xlPrintErrorsDisplayed
.OddAndEvenPagesHeaderFooter = False
.DifferentFirstPageHeaderFooter = False
.ScaleWithDocHeaderFooter = True
.AlignMarginsHeaderFooter = True
.EvenPage.LeftHeader.Text = ""
.EvenPage.CenterHeader.Text = ""
.EvenPage.RightHeader.Text = ""
.EvenPage.LeftFooter.Text = ""
.EvenPage.CenterFooter.Text = ""
.EvenPage.RightFooter.Text = ""
.FirstPage.LeftHeader.Text = ""
.FirstPage.CenterHeader.Text = ""
.FirstPage.RightHeader.Text = ""
.FirstPage.LeftFooter.Text = ""
.FirstPage.CenterFooter.Text = ""
.FirstPage.RightFooter.Text = ""
End With
Range("R7:S7").Select
Selection.Copy
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Application.CutCopyMode = False
Selection.NumberFormat = "0"
Range("A4:H9").Select
Selection.Copy
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Rows("10:10").Select
Selection.EntireRow.Hidden = True
Application.PrintCommunication = True
'the new sheet should be named to this specific cel value (this is the name we copied form sheet(1) from thisworkbook
'now it is referring to a specific sheet of wbnew, but that is not ok, should be changed
Sheets(2).Name = Range("M5").Value
Range("A15").Select
'later I have to Call here an other Sub in order to do aditional extractions
Call sub_followlater
wbnew.Activate
'create a new sheet here
set wsNew = wbNew.Sheets.Add After:=ActiveSheet
'save the new workbook wbnew
wbnew.SaveAs Filename:= _
"C:\Path\" & "per 1-15" & " " & Format(Range("C13"), "mmmm") & " " & Format(Range("C13"), "YYYY") & ".xlsx"
FileFormat = xlOpenXMLWorkbook
ActiveWindow.Close
Hopefully someone is feeling challanged enouhg to help me out with this.
thanks in advance...
One solution is to write a macro that will copy the rows with data to another sheet, so you get all the entries for all jobs, all dates on one page. This will streamline the code because you will not be looking at blank rows for your report preparation.
Once you have the data all transferred to a single worksheet you can loop through the rows in a second macro that copies the data to separate pages based on the persons name.
This involves a good amount of skill in VBA using loops to evaluate and copy the rows from many tabs to one in the first pass, then from the one worksheet to many in the second pass. You will not be able to complete this with just the macro recorder. If you are up to the challenge but lacking in knowledge of the VBA language and the Excel object model I suggest getting one of John Walkenbach's books on Excel Power Programming with VBA.
Good luck.

Resources