I am working on code to basically go through each sheet in my Workbook, and then selection delete and at finish save all worksheets to csv. I don't receive any errors, but it also only save worksheets.
Any help is greatly appreciated!
Public Sub SaveWorksheetsAsCsv()
Dim xWs As Worksheet
Dim xDir As String
Dim folder As FileDialog
Set folder = Application.FileDialog(msoFileDialogFolderPicker)
If folder.Show <> -1 Then Exit Sub
xDir = folder.SelectedItems(1)
For Each xWs In Application.ActiveWorkbook.Worksheets
With xWs
Range("A3").Select
Range(Selection, Selection.End(xlToRight)).Select
Range(Selection, Selection.End(xlDown)).Select
Selection.Copy
Range("AU1").Select
Selection.PasteSpecial Paste:=xlPasteValuesAndNumberFormats, Operation:= _
xlNone, SkipBlanks:=False, Transpose:=False
Columns("A:AT").Select
Range("AT1").Activate
Application.CutCopyMode = False
Selection.Delete Shift:=xlToLeft
Range("A1").Select
Cells.Replace What:="(puste)", Replacement:="", LookAt:=xlPart, _
SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
ReplaceFormat:=False, FormulaVersion:=xlReplaceFormula2
End With
xWs.SaveAs Filename:=xDir & "\" & xWs.Name, FileFormat:=xlCSV, Local:=True
Next
End Sub
When using With prefix ranges with a dot.
Option Explicit
Public Sub SaveWorksheetsAsCsv()
Dim xWs As Worksheet, xDir As String, msg As String
Dim folder As FileDialog
Set folder = Application.FileDialog(msoFileDialogFolderPicker)
If folder.Show <> -1 Then Exit Sub
xDir = folder.SelectedItems(1)
Application.ScreenUpdating = False
For Each xWs In Application.ActiveWorkbook.Worksheets
With xWs
msg = msg & vbCrLf & xWs.Name
.Range(.Range("A3"), .Range("A3").End(xlToRight).End(xlDown)).Copy
.Range("AU1").PasteSpecial Paste:=xlPasteValuesAndNumberFormats, Operation:= _
xlNone, SkipBlanks:=False, Transpose:=False
Application.CutCopyMode = False
.Columns("A:AT").Delete Shift:=xlToLeft
.UsedRange.Cells.Replace What:="(puste)", Replacement:="", LookAt:=xlPart, _
SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
ReplaceFormat:=False ', FormulaVersion:=xlReplaceFormula2
.SaveAs Filename:=xDir & "\" & .Name, FileFormat:=xlCSV, Local:=True
'.Activate ' optional
'.Range("A1").Select ' optional
End With
Next
Application.ScreenUpdating = True
MsgBox "Sheets saved :" & msg, vbInformation
End Sub
Related
My code is
Sub Macro5()
'
' Macro5 Macro
'
Range("A7").Select
Range(Selection, Selection.End(xlToRight)).Select
Range(Selection, Selection.End(xlDown)).Select
Selection.Columns.AutoFit
Range("A8").Select
Application.CutCopyMode = False
ActiveCell.FormulaR1C1 = "=R4C2"
Range("A8").Select
Selection.Copy
Range(Selection, Selection.End(xlDown)).Select
ActiveSheet.Paste
Range("A7").Select
Range(Selection, Selection.End(xlToRight)).Select
Range(Selection, Selection.End(xlDown)).Select
Application.CutCopyMode = False
Selection.AutoFilter
Selection.Columns.AutoFit
ActiveWindow.SmallScroll ToRight:=15
ActiveSheet.Range("$A$7:$AC$38").AutoFilter Field:=20, Criteria1:="0"
ActiveSheet.Range("$A$7:$AC$38").AutoFilter Field:=22, Criteria1:="0"
ActiveWindow.SmallScroll ToRight:=-45
Range("A13").Select
Range(Selection, Selection.End(xlToRight)).Select
Range(Selection, Selection.End(xlDown)).Select
Selection.EntireRow.Delete
Cells.Select
Range("A22").Activate
Selection.AutoFilter
Range("A11").Select
Columns("E:E").Select
Application.CutCopyMode = False
Selection.Replace What:="Discovery Ads", Replacement:="Qua" & ChrW(777) & "ng Ca" & ChrW(769) & "o Kha" _
& ChrW(769) & "m Pha" & ChrW(769) _
, LookAt:=xlPart, SearchOrder:=xlByRows, MatchCase:=False, SearchFormat _
:=False, ReplaceFormat:=False, FormulaVersion:=xlReplaceFormula2
Columns("E:E").Select
Selection.Replace What:="Product Search Ad", Replacement:= _
"Qua" & ChrW(777) & "ng Ca" & ChrW(769) & "o Ti" _
& ChrW(768) & "m Kiê" & ChrW(769) & "m Sa" & ChrW(777) & "n Phâ" & ChrW( _
777) & "m", LookAt:=xlPart, SearchOrder:=xlByRows, _
MatchCase:=False, SearchFormat:=False, ReplaceFormat:=False, _
FormulaVersion:=xlReplaceFormula2
Columns("E:E").Select
Selection.Replace What:="Shop Search Ad", Replacement:= _
"Qua" & ChrW(777) & "ng Ca" & ChrW(769) & "o Ti" _
& ChrW(768) & "m Kiê" & ChrW(769) & "m Shop", LookAt:=xlPart, SearchOrder:=xlByRows, _
MatchCase:=False, SearchFormat:=False, ReplaceFormat:=False, _
FormulaVersion:=xlReplaceFormula2
Selection.AutoFilter
End Sub
So i have insert this code before code
Dim ws As Worksheet
For Each ws In Sheets
And insert more prepend every Range...Select like
ws.Range("A7").Select
But it not work for me. So is there any other way to do it?. Loop VBA all sheet in that workbook except "MasterSheet"
About my data it look like this :
enter image description here
So i wanna change A7:A end down is value B4.
-Then filter, Filter column T,V every value = 0 and delete it
Replace some name
And this is final after run marco 1 sheet :
enter image description here
enter image description here
This is how I would normally loop through all sheets with an exception:
Sub loop_through_sheets()
Dim ws As Worksheet
For Each ws In Sheets
If ws.Name <> "Mastersheet" Then
'... run the code on ws
Else
'.. do nothing
End If
Next
End Sub
Your code to run on ws might look something like this:
With ws
'auto fit the columns
.Range("A:AC").Columns.AutoFit
'find the last populated cell in column A
Dim lastrow as Long
lastrow=ws.Cells(ws.Rows.Count, "A").End(xlUp).Row
'insert the formula
.Range("A8:A" & lastrow).FormulaR1C1 = "=R4C2"
'etc. etc.
End with
of course this is not the cleanest and best solution (see comment "avoid select...."), but leave the code as is it, make a sub for calling it like:
sub callmymacro
Dim ws As Worksheet
For Each ws In Sheets
if ws.Name = "Mastersheet" GoTo notthisone
Sheets(ws).Select
call Macro5
notthisone:
Next
end sub
Just wondering if anyone can help me clean up my code. It currently works perfectly for what I need it to do. Just wondering if it can run faster. Right now it seems to open and close each workbook 3 times before moving to the next one.
Sub JanuaryMacro()
Dim strF As String, strP As String
Dim wb As Workbook
Range("B2:M2").clearcontents
'Edit this declaration to your folder name
strP = "\\My path" 'change for the path of your folder
strF = Dir(strP & "\*.xlsx")
Application.DisplayAlerts = False
Application.AskToUpdateLinks = False
Do While strF <> vbNullString
Set wb = Workbooks.Open(strP & "\" & strF)
Range("Totals").Select
Selection.Copy
Windows("Monthly Report.xlsm").Activate
Range("D2:M2").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlAdd, SkipBlanks _
:=False, Transpose:=False
Set wb = Workbooks.Open(strP & "\" & strF)
Range("FG_Approvals").Select
Selection.Copy
Windows("Monthly Report.xlsm").Activate
Range("C2").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlAdd, SkipBlanks _
:=False, Transpose:=False
Set wb = Workbooks.Open(strP & "\" & strF)
Range("Allocations").Select
Selection.Copy
Windows("Monthly Report.xlsm").Activate
Range("B2").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlAdd, SkipBlanks _
:=False, Transpose:=False
wb.Close SaveChanges:=False
strF = Dir()
Loop
Application.DisplayAlerts = True
End Sub
You should use references to your monthly-report-sheet, the new workbook and its sheet e. g. like this:
Sub JanuaryMacroVersion2()
Dim strF As String, strP As String
Dim mr As Worksheet
Dim wb As Workbook, ws As Worksheet
Set mr = ActiveSheet ' your monthly report
mr.Range("B2:M2").ClearContents
strP = "\\My path" 'change for the path of your folder
strF = Dir(strP & "\*.xlsx")
Application.DisplayAlerts = False
Application.AskToUpdateLinks = False
Do While strF <> vbNullString
Set wb = Workbooks.Open(strP & "\" & strF)
Set ws = ActiveSheet
ws.Range("Totals").Copy
mr.Range("D2:M2").PasteSpecial _
Paste:=xlPasteValues, Operation:=xlAdd, _
SkipBlanks:=False, Transpose:=False
ws.Range("FG_Approvals").Copy
mr.Range("C2").PasteSpecial _
Paste:=xlPasteValues, Operation:=xlAdd, _
SkipBlanks:=False, Transpose:=False
ws.Range("Allocations").Copy
mr.Range("B2").PasteSpecial _
Paste:=xlPasteValues, Operation:=xlAdd, _
SkipBlanks:=False, Transpose:=False
wb.Close SaveChanges:=False
strF = Dir()
Loop
Application.DisplayAlerts = True
End Sub
If the range names like "FG_Approvals" refer to a workbook wide name, replace ws.Range("FG_Approvals")by wb.Range("FG_Approvals").
Next optimization step would be omitting copy/paste by assigning their Range.Value directly:
Sub JanuaryMacroVersion3()
Dim strF As String, strP As String
Dim mr As Worksheet
Dim wb As Workbook, ws As Worksheet
Dim lastRow As Long
Set mr = ActiveSheet
mr.Range("B2:M2").ClearContents
strP = "\\My path" 'change for the path of your folder
strF = Dir(strP & "\*.xlsx")
Application.DisplayAlerts = False
Application.AskToUpdateLinks = False
Do While strF <> vbNullString
Set wb = Workbooks.Open(strP & "\" & strF)
Set ws = ActiveSheet
lastRow = mr.Cells(mr.Rows.Count, "D").End(xlUp).Row
mr.Cells(lastRow + 1, "D").Resize _
(ws.Range("Totals").Rows.Count, _
ws.Range("Totals").Columns.Count).Value _
= ws.Range("Totals").Value
lastRow = mr.Cells(mr.Rows.Count, "C").End(xlUp).Row
mr.Cells(lastRow + 1, "C").Resize _
(ws.Range("FG_Approvals").Rows.Count, _
ws.Range("FG_Approvals").Columns.Count).Value _
= ws.Range("FG_Approvals").Value
lastRow = mr.Cells(mr.Rows.Count, "B").End(xlUp).Row
mr.Cells(lastRow + 1, "B").Resize _
(ws.Range("Allocations").Rows.Count, _
ws.Range("Allocations").Columns.Count).Value _
= ws.Range("Allocations").Value
wb.Close SaveChanges:=False
strF = Dir()
Loop
Application.DisplayAlerts = True
End Sub
I have sheets with names such as M&MFIN.NS, M&M.NS, L&TFH.NS, i'm trying to find one of them and then do the specific task.
However, if one of the above mentioned sheet is not found, the code terminates(Exit Sub).
i need help, if sheet not found it should go to next search option, and then rest of the code
Please guide
Sub SearchSheetNameandcreatenewsheet()
Application.Calculation = xlCalculationManual
Application.ScreenUpdating = False
Application.DisplayAlerts = False
Dim sName As String
Dim sFound As Boolean
sName = "M&MFIN.NS"
If sName = "" Then Exit Sub
sFound = False
On Error Resume Next
ActiveWorkbook.Sheets(sName).Select
Range(Range("E3"), Range("E3").End(xlDown)).Select
Selection.Copy
Worksheets("Close Price").Activate
Cells.Find(What:="M&MFIN.NS", After:=ActiveCell, LookIn:=xlFormulas, _
LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
MatchCase:=False, SearchFormat:=False).Activate
ActiveCell.Offset(1, 0).Range("A1").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Dim sName1 As String
Dim sFound1 As Boolean
sName1 = "M&M.NS"
If sName1 = "" Then Exit Sub
sFound1 = False
On Error Resume Next
ActiveWorkbook.Sheets(sName1).Select
Range(Range("E3"), Range("E3").End(xlDown)).Select
Selection.Copy
Worksheets("Close Price").Activate
Cells.Find(What:="M&M.NS", After:=ActiveCell, LookIn:=xlFormulas, _
LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
MatchCase:=False, SearchFormat:=False).Activate
ActiveCell.Offset(1, 0).Range("A1").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Dim sName2 As String
Dim sFound2 As Boolean
sName2 = "L&TFH.NS"
If sName2 = "" Then Exit Sub
sFound2 = False
On Error Resume Next
ActiveWorkbook.Sheets(sName2).Select
Range(Range("E3"), Range("E3").End(xlDown)).Select
Selection.Copy
Worksheets("Close Price").Activate
Cells.Find(What:="L&TFH.NS", After:=ActiveCell, LookIn:=xlFormulas, _
LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
MatchCase:=False, SearchFormat:=False).Activate
ActiveCell.Offset(1, 0).Range("A1").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Range("A1").CurrentRegion.Select
Selection.Replace What:="null", Replacement:="", LookAt:=xlPart, _
SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
ReplaceFormat:=False
'"creating close price sheet seperataly"
Sheets("Close Price").Select
Sheets("Close Price").Copy
ChDir "C:\Lookback Momentum Analysis"
ActiveWorkbook.SaveAs Filename:= _
"C:\Lookback Momentum Analysis\Close Price.xlsx", FileFormat:= _
xlOpenXMLWorkbook, CreateBackup:=False
ActiveWindow.Close
Application.Calculation = xlCalculationAutomatic
Application.ScreenUpdating = True
Application.DisplayAlerts = True
Worksheets("Parameters").Activate
End Sub
This would be an option:
Option Explicit
Sub SearchSheetNameandcreatenewsheet()
Application.Calculation = xlCalculationManual
Application.ScreenUpdating = False
Application.DisplayAlerts = False
Dim wb As Workbook, ws As Worksheet
Set wb = ThisWorkbook 'the workbook which has the code
For Each ws In wb.Worksheets
Select Case ws.Name
Case "M&MFIN.NS"
'code
Case "M&M.NS"
'code
Case "L&TFH.NS"
'code
End Select
Next ws
End Sub
You only need to feed the sheet names and introduce your code below every Case for especific worksheet names.
Firstly I am a newbie when it comes to coding, but am giving it a go to see how it can help me dig down into my data.
I am currently looking at capturing time-sheet data for different team members and copying it into a master summary workbook.
I recorded my macro and then re-organised things a bit to make the code cleaner (this may be where I went wrong). But now when I run my macro I get a Run-time error '9': Subscript out of range.
my code is as follows:
Option Explicit
Sub MergeAll()
' Open all Timesheets
Workbooks.Open Filename:= _
"S:\UFD\24 Reports\02 Time Keeping\PT Time Sheets\2016_JAMAL.xlsx"
Workbooks.Open Filename:= _
"S:\UFD\24 Reports\02 Time Keeping\PT Time Sheets\2016_LOKESH.xlsx"
Workbooks.Open Filename:= _
"S:\UFD\24 Reports\02 Time Keeping\PT Time Sheets\2016_NONI.xlsx"
Workbooks.Open Filename:= _
"S:\UFD\24 Reports\02 Time Keeping\PT Time Sheets\2016_RAJESH.xlsx"
Workbooks.Open Filename:= _
"S:\UFD\24 Reports\02 Time Keeping\PT Time Sheets\2016_SANTHOSH.xlsx"
Workbooks.Open Filename:= _
"S:\UFD\24 Reports\02 Time Keeping\PT Time Sheets\2016_7.xlsx"
Workbooks.Open Filename:= _
"S:\UFD\24 Reports\02 Time Keeping\PT Time Sheets\2016_8.xlsx"
Workbooks.Open Filename:= _
"S:\UFD\24 Reports\02 Time Keeping\PT Time Sheets\2016_9.xlsx"
' Activate and Copy Data
Windows("2016_JAMAL.xlsx").Activate
Range("G2:J2").Select
Selection.Copy
Windows("master.xlsm").Activate
Range("C2:F2").Select
ActiveSheet.Paste
Windows("2016_LOKESH.xlsx").Activate
Range("G2:J2").Select
Selection.Copy
Windows("master.xlsm").Activate
Range("C2:F2").Select
ActiveSheet.Paste
Windows("2016_NONI.xlsx").Activate
Range("G2:J2").Select
Selection.Copy
Windows("master.xlsm").Activate
Range("C2:F2").Select
ActiveSheet.Paste
Windows("2016_RAJESH.xlsx").Activate
Range("G2:J2").Select
Selection.Copy
Windows("master.xlsm").Activate
Range("C2:F2").Select
ActiveSheet.Paste
Windows("2016_SANTHOSH.xlsx").Activate
Range("G2:J2").Select
Selection.Copy
Windows("master.xlsm").Activate
Range("C2:F2").Select
ActiveSheet.Paste
Windows("2016_WARREN.xlsx").Activate
Range("G2:J2").Select
Selection.Copy
Windows("master.xlsm").Activate
Range("C2:F2").Select
ActiveSheet.Paste
Windows("2016_7.xlsx").Activate
Range("G2:J2").Select
Selection.Copy
Windows("master.xlsm").Activate
Range("C2:F2").Select
ActiveSheet.Paste
Windows("2016_8.xlsx").Activate
Range("G2:J2").Select
Selection.Copy
Windows("master.xlsm").Activate
Range("C2:F2").Select
ActiveSheet.Paste
Windows("2016_9.xlsx").Activate
Range("G2:J2").Select
Selection.Copy
Windows("master.xlsm").Activate
Range("C2:F2").Select
ActiveSheet.Paste
' Close all Timesheets
Windows("2016_JAMAL.xlsx").Activate
ActiveWindow.Close
Windows("2016_LOKESH.xlsx").Activate
ActiveWindow.Close
Windows("2016_NONI.xlsx").Activate
ActiveWindow.Close
Windows("2016_RAJESH.xlsx").Activate
ActiveWindow.Close
Windows("2016_SANTHOSH.xlsx").Activate
ActiveWindow.Close
Windows("2016_WARREN.xlsx").Activate
ActiveWindow.Close
Windows("2016_7.xlsx").Activate
ActiveWindow.Close
Windows("2016_8.xlsx").Activate
ActiveWindow.Close
Windows("2016_9.xlsx").Activate
ActiveWindow.Close
End Sub
Now I took out some code which was appearing in each line, after the Windows("filename").Activate line. This was:
ActiveWindow.SmallScroll Down:=-18
As I believe that this was only when I scrolled up to the correct place and depending on which was the active cell prior to saving each time, this would change.
I am out of ideas and any help would be much appreciated.
For the record, I have so far tried several different methods - including copying and pasting code from sites, following you tube tutorial videos, but each time and each method, the same error occurs.
Thanks in advance,
Rich
UPDATE
I re-recorded the macro and simply changed the order of what I did during the record. I no longer get the error. However the code is very messy and long winded. The screen flickers a lot during the process too. is there a way to make it a smoother experience for the user? The new code is below
Sub MergeAll2()
'
' MergeAll2 Macro
'
'
' Open All
Workbooks.Open Filename:= _
"S:\UFD\24 Reports\02 Time Keeping\PT Time Sheets\2016_7.xlsx"
Workbooks.Open Filename:= _
"S:\UFD\24 Reports\02 Time Keeping\PT Time Sheets\2016_8.xlsx"
Workbooks.Open Filename:= _
"S:\UFD\24 Reports\02 Time Keeping\PT Time Sheets\2016_9.xlsx"
Workbooks.Open Filename:= _
"S:\UFD\24 Reports\02 Time Keeping\PT Time Sheets\2016_JAMAL.xlsx"
Workbooks.Open Filename:= _
"S:\UFD\24 Reports\02 Time Keeping\PT Time Sheets\2016_LOKESH.xlsx"
Workbooks.Open Filename:= _
"S:\UFD\24 Reports\02 Time Keeping\PT Time Sheets\2016_NONI.xlsx"
Workbooks.Open Filename:= _
"S:\UFD\24 Reports\02 Time Keeping\PT Time Sheets\2016_RAJESH.xlsx"
Workbooks.Open Filename:= _
"S:\UFD\24 Reports\02 Time Keeping\PT Time Sheets\2016_SANTHOSH.xlsx"
Workbooks.Open Filename:= _
"S:\UFD\24 Reports\02 Time Keeping\PT Time Sheets\2016_WARREN.xlsx"
' Copy & Paste
Windows("2016_JAMAL.xlsx").Activate
Range("G2:J2").Select
Selection.Copy
Windows("master.xlsm").Activate
Range("C2").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Windows("2016_LOKESH.xlsx").Activate
Range("G2:J2").Select
Application.CutCopyMode = False
Selection.Copy
Windows("master.xlsm").Activate
Range("C3:F3").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Windows("2016_NONI.xlsx").Activate
Range("G2:J2").Select
Application.CutCopyMode = False
Selection.Copy
Windows("master.xlsm").Activate
Range("C4").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Windows("2016_RAJESH.xlsx").Activate
Range("G2:J2").Select
Application.CutCopyMode = False
Selection.Copy
Windows("master.xlsm").Activate
Range("C5").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Windows("2016_SANTHOSH.xlsx").Activate
Range("G2:J2").Select
Application.CutCopyMode = False
Selection.Copy
Windows("master.xlsm").Activate
Range("C6").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Windows("2016_WARREN.xlsx").Activate
Range("G2:J2").Select
Application.CutCopyMode = False
Selection.Copy
Windows("master.xlsm").Activate
Range("C7").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Windows("2016_7.xlsx").Activate
Range("G2:J2").Select
Application.CutCopyMode = False
Selection.Copy
Windows("master.xlsm").Activate
Range("C8").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Windows("2016_8.xlsx").Activate
Range("G2:J2").Select
Application.CutCopyMode = False
Selection.Copy
Windows("master.xlsm").Activate
Range("C9").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Windows("2016_9.xlsx").Activate
Range("G2:J2").Select
Application.CutCopyMode = False
Selection.Copy
Windows("master.xlsm").Activate
Range("C10").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
' Close All
Windows("2016_JAMAL.xlsx").Activate
ActiveWindow.Close
Windows("2016_LOKESH.xlsx").Activate
ActiveWindow.Close
Windows("2016_NONI.xlsx").Activate
ActiveWindow.Close
Windows("2016_RAJESH.xlsx").Activate
ActiveWindow.Close
Windows("2016_SANTHOSH.xlsx").Activate
ActiveWindow.Close
Windows("2016_WARREN.xlsx").Activate
ActiveWindow.Close
Windows("2016_7.xlsx").Activate
ActiveWindow.Close
Windows("2016_8.xlsx").Activate
ActiveWindow.Close
Windows("2016_9.xlsx").Activate
ActiveWindow.Close
End Sub
UPDATE 2
Many thanks for the help so far. I am looking to edit this line:
Workbooks("master").ActiveSheet.Range("C2:F2").Value = Workbooks("2016_JAMAL").ActiveSheet.Range("G2:J2").Value
So that I can choose which sheet in "master" to write it to and also which sheet in "2016_JAMAL" to copy it from.
Secondly, I want to copy from two ranges on this sheet - C2:G2 and C5:G56
I would like to do this in a streamlined way.
Many thanks for your answers so far - I will read the information on Arrays and work through the 5 pages!
Rich
You can stop the flickering screen by setting the following:
Application.ScreenUpdating = False
Add that to your macro and run it again.
You should be able to speed up your "Copy & Paste" section by using this instead:
With Workbooks("master").ActiveSheet
.Range("C2:F2").Value = Workbooks("2016_JAMAL").ActiveSheet.Range("G2:J2").Value
.Range("C3:F3").Value = Workbooks("2016_LOKESH").ActiveSheet.Range("G2:J2").Value
.Range("C4:F4").Value = Workbooks("2016_NONI").ActiveSheet.Range("G2:J2").Value
.Range("C5:F5").Value = Workbooks("2016_RAJESH").ActiveSheet.Range("G2:J2").Value
.Range("C6:F6").Value = Workbooks("2016_SANTHOSH").ActiveSheet.Range("G2:J2").Value
.Range("C7:F7").Value = Workbooks("2016_WARREN").ActiveSheet.Range("G2:J2").Value
.Range("C8:F8").Value = Workbooks("2016_7").ActiveSheet.Range("G2:J2").Value
.Range("C9:F9").Value = Workbooks("2016_8").ActiveSheet.Range("G2:J2").Value
.Range("C10:F10").Value = Workbooks("2016_9").ActiveSheet.Range("G2:J2").Value
End With
You could also make your "close" part simpler by using:
Workbooks("2016_JAMAL.xlsx").Close False
Workbooks("2016_LOKESH.xlsx").Close False
Workbooks("2016_NONI.xlsx").Close False
Workbooks("2016_RAJESH.xlsx").Close False
Workbooks("2016_SANTHOSH.xlsx").Close False
Workbooks("2016_WARREN.xlsx").Close False
Workbooks("2016_7.xlsx").Close False
Workbooks("2016_8.xlsx").Close False
Workbooks("2016_9.xlsx").Close False
I used Activesheet not knowing how many sheets each workbook has or their names. You can adjust accordingly. Here's my version:
Option Explicit
Sub MergeAll2()
Dim wb2016_7 As Workbook
Dim wb2016_8 As Workbook
Dim wb2016_9 As Workbook
Dim wb2016_JAMAL As Workbook
Dim wb2016_LOKESH As Workbook
Dim wb2016_NONI As Workbook
Dim wb2016_RAJESH As Workbook
Dim wb2016_SANTHOSH As Workbook
Dim wb2016_WARREN As Workbook
Dim strPath As String
Application.ScreenUpdating = False
strPath = "S:\UFD\24 Reports\02 Time Keeping\PT Time Sheets\"
Set wb2016_7 = Workbooks.Open(Filename:=strPath & "2016_7.xlsx")
Set wb2016_8 = Workbooks.Open(Filename:=strPath & "2016_8.xlsx")
Set wb2016_9 = Workbooks.Open(Filename:=strPath & "2016_9.xlsx")
Set wb2016_JAMAL = Workbooks.Open(Filename:=strPath & "2016_JAMAL.xlsx")
Set wb2016_LOKESH = Workbooks.Open(Filename:=strPath & "2016_LOKESH.xlsx")
Set wb2016_NONI = Workbooks.Open(Filename:=strPath & "2016_NONI.xlsx")
Set wb2016_RAJESH = Workbooks.Open(Filename:=strPath & "2016_RAJESH.xlsx")
Set wb2016_SANTHOSH = Workbooks.Open(Filename:=strPath & "2016_SANTHOSH.xlsx")
Set wb2016_WARREN = Workbooks.Open(Filename:=strPath & "2016_WARREN.xlsx")
With Workbooks("master").ActiveSheet
.Range("C2:F2").Value = wb2016_JAMAL.ActiveSheet.Range("G2:J2").Value
.Range("C3:F3").Value = wb2016_LOKESH.ActiveSheet.Range("G2:J2").Value
.Range("C4:F4").Value = wb2016_NONI.ActiveSheet.Range("G2:J2").Value
.Range("C5:F5").Value = wb2016_RAJESH.ActiveSheet.Range("G2:J2").Value
.Range("C6:F6").Value = wb2016_SANTHOSH.ActiveSheet.Range("G2:J2").Value
.Range("C7:F7").Value = wb2016_WARREN.ActiveSheet.Range("G2:J2").Value
.Range("C8:F8").Value = wb2016_7.ActiveSheet.Range("G2:J2").Value
.Range("C9:F9").Value = wb2016_8.ActiveSheet.Range("G2:J2").Value
.Range("C10:F10").Value = wb2016_9.ActiveSheet.Range("G2:J2").Value
End With
wb2016_7.Close True
wb2016_8.Close True
wb2016_9.Close True
wb2016_JAMAL.Close True
wb2016_LOKESH.Close True
wb2016_NONI.Close True
wb2016_RAJESH.Close True
wb2016_SANTHOSH.Close True
wb2016_WARREN.Close True
Set wb2016_7 = Nothing
Set wb2016_8 = Nothing
Set wb2016_9 = Nothing
Set wb2016_JAMAL = Nothing
Set wb2016_LOKESH = Nothing
Set wb2016_NONI = Nothing
Set wb2016_RAJESH = Nothing
Set wb2016_SANTHOSH = Nothing
Set wb2016_WARREN = Nothing
Application.ScreenUpdating = True
End Sub
It's good practice to use Option Explicit which forces you to declare your variables and to set your objects back to Nothing after using them.
EDIT
I would replace Activesheet with Sheets("SheetName") for each of the workbooks. Otherwise you could put the following code in the workbook object for every workbook (and save them all as macro enabled), except master, and keep Activesheet:
Private Sub Workbook_Open( )
Sheets ("SheetName").Activate
End Sub
I would, at least, change Workbooks("master").ActiveSheet to Workbooks("master").Sheets("SheetName") or you'll need to remember to run it from the correct (that is, active) sheet. This is a very helpful link, also.
This will merge a range from all workbooks in a folder (next data set goes below prior).
Sub Basic_Example_1()
Dim MyPath As String, FilesInPath As String
Dim MyFiles() As String
Dim SourceRcount As Long, Fnum As Long
Dim mybook As Workbook, BaseWks As Worksheet
Dim sourceRange As Range, destrange As Range
Dim rnum As Long, CalcMode As Long
'Fill in the path\folder where the files are
MyPath = "C:\Users\Ron\test"
'Add a slash at the end if the user forget it
If Right(MyPath, 1) <> "\" Then
MyPath = MyPath & "\"
End If
'If there are no Excel files in the folder exit the sub
FilesInPath = Dir(MyPath & "*.xl*")
If FilesInPath = "" Then
MsgBox "No files found"
Exit Sub
End If
'Fill the array(myFiles)with the list of Excel files in the folder
Fnum = 0
Do While FilesInPath <> ""
Fnum = Fnum + 1
ReDim Preserve MyFiles(1 To Fnum)
MyFiles(Fnum) = FilesInPath
FilesInPath = Dir()
Loop
'Change ScreenUpdating, Calculation and EnableEvents
With Application
CalcMode = .Calculation
.Calculation = xlCalculationManual
.ScreenUpdating = False
.EnableEvents = False
End With
'Add a new workbook with one sheet
Set BaseWks = Workbooks.Add(xlWBATWorksheet).Worksheets(1)
rnum = 1
'Loop through all files in the array(myFiles)
If Fnum > 0 Then
For Fnum = LBound(MyFiles) To UBound(MyFiles)
Set mybook = Nothing
On Error Resume Next
Set mybook = Workbooks.Open(MyPath & MyFiles(Fnum))
On Error GoTo 0
If Not mybook Is Nothing Then
On Error Resume Next
With mybook.Worksheets(1)
Set sourceRange = .Range("A1:C1")
End With
If Err.Number > 0 Then
Err.Clear
Set sourceRange = Nothing
Else
'if SourceRange use all columns then skip this file
If sourceRange.Columns.Count >= BaseWks.Columns.Count Then
Set sourceRange = Nothing
End If
End If
On Error GoTo 0
If Not sourceRange Is Nothing Then
SourceRcount = sourceRange.Rows.Count
If rnum + SourceRcount >= BaseWks.Rows.Count Then
MsgBox "Sorry there are not enough rows in the sheet"
BaseWks.Columns.AutoFit
mybook.Close savechanges:=False
GoTo ExitTheSub
Else
'Copy the file name in column A
With sourceRange
BaseWks.cells(rnum, "A"). _
Resize(.Rows.Count).Value = MyFiles(Fnum)
End With
'Set the destrange
Set destrange = BaseWks.Range("B" & rnum)
'we copy the values from the sourceRange to the destrange
With sourceRange
Set destrange = destrange. _
Resize(.Rows.Count, .Columns.Count)
End With
destrange.Value = sourceRange.Value
rnum = rnum + SourceRcount
End If
End If
mybook.Close savechanges:=False
End If
Next Fnum
BaseWks.Columns.AutoFit
End If
ExitTheSub:
'Restore ScreenUpdating, Calculation and EnableEvents
With Application
.ScreenUpdating = True
.EnableEvents = True
.Calculation = CalcMode
End With
End Sub
This will merge a range from all workbooks in a folder (next data set goes to the right of prior).
Sub Basic_Example_3()
Dim MyPath As String, FilesInPath As String
Dim MyFiles() As String
Dim SourceCcount As Long, Fnum As Long
Dim mybook As Workbook, BaseWks As Worksheet
Dim sourceRange As Range, destrange As Range
Dim Cnum As Long, CalcMode As Long
'Fill in the path\folder where the files are
MyPath = "C:\Users\Ron\test"
'Add a slash at the end if the user forget it
If Right(MyPath, 1) <> "\" Then
MyPath = MyPath & "\"
End If
'If there are no Excel files in the folder exit the sub
FilesInPath = Dir(MyPath & "*.xl*")
If FilesInPath = "" Then
MsgBox "No files found"
Exit Sub
End If
'Fill the array(myFiles)with the list of Excel files in the folder
Fnum = 0
Do While FilesInPath <> ""
Fnum = Fnum + 1
ReDim Preserve MyFiles(1 To Fnum)
MyFiles(Fnum) = FilesInPath
FilesInPath = Dir()
Loop
'Change ScreenUpdating, Calculation and EnableEvents
With Application
CalcMode = .Calculation
.Calculation = xlCalculationManual
.ScreenUpdating = False
.EnableEvents = False
End With
'Add a new workbook with one sheet
Set BaseWks = Workbooks.Add(xlWBATWorksheet).Worksheets(1)
Cnum = 1
'Loop through all files in the array(myFiles)
If Fnum > 0 Then
For Fnum = LBound(MyFiles) To UBound(MyFiles)
Set mybook = Nothing
On Error Resume Next
Set mybook = Workbooks.Open(MyPath & MyFiles(Fnum))
On Error GoTo 0
If Not mybook Is Nothing Then
On Error Resume Next
Set sourceRange = mybook.Worksheets(1).Range("A1:A10")
If Err.Number > 0 Then
Err.Clear
Set sourceRange = Nothing
Else
'if SourceRange use all rows then skip this file
If sourceRange.Rows.Count >= BaseWks.Rows.Count Then
Set sourceRange = Nothing
End If
End If
On Error GoTo 0
If Not sourceRange Is Nothing Then
SourceCcount = sourceRange.Columns.Count
If Cnum + SourceCcount >= BaseWks.Columns.Count Then
MsgBox "Sorry there are not enough columns in the sheet"
BaseWks.Columns.AutoFit
mybook.Close savechanges:=False
GoTo ExitTheSub
Else
'Copy the file name in the first row
With sourceRange
BaseWks.cells(1, Cnum). _
Resize(, .Columns.Count).Value = MyFiles(Fnum)
End With
'Set the destrange
Set destrange = BaseWks.cells(2, Cnum)
'we copy the values from the sourceRange to the destrange
With sourceRange
Set destrange = destrange. _
Resize(.Rows.Count, .Columns.Count)
End With
destrange.Value = sourceRange.Value
Cnum = Cnum + SourceCcount
End If
End If
mybook.Close savechanges:=False
End If
Next Fnum
BaseWks.Columns.AutoFit
End If
ExitTheSub:
'Restore ScreenUpdating, Calculation and EnableEvents
With Application
.ScreenUpdating = True
.EnableEvents = True
.Calculation = CalcMode
End With
End Sub
Sub forEachWs()
Dim Ws As Worksheet
Windows("XYZSheet.xlsx").Activate
For Each Ws In ActiveWorkbook.Worksheets
Range("E1").Select
ActiveCell.FormulaR1C1 = "=SUM(C[-2])"
Range("D2").Select
ActiveCell.FormulaR1C1 = "=(RC[-1]/R1C5)"
Range("D2").Select
Selection.Copy
Range("D2:D2450").Select
ActiveSheet.Paste
Application.CutCopyMode = False
Columns("D:D").Select
Range("D2").Activate
Selection.Copy
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Application.CutCopyMode = False
Selection.Replace What:="0", Replacement:="", LookAt:=xlWhole, _
SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
ReplaceFormat:=False
Next Ws
End Sub
The code does not loop through the other tabs within the Sheets of
Workbook "XYZSheet.xlsx" and I cannot seem to understand why.
The code in the middle from "Range(E1)" all the way to "ReplaceFormat:=False" are all through a recorded session with minor edits.
I don't fully understand VBA code apart from cycling through it with F8, so please go easy on me!
Thanks!
You need something like:
Sub forEachWs()
Dim Ws As Worksheet
Windows("XYZSheet.xlsx").Activate
For Each Ws In ActiveWorkbook.Worksheets
With Ws
.Range("E1").FormulaR1C1 = "=SUM(C[-2])"
.Range("D2").FormulaR1C1 = "=(RC[-1]/R1C5)"
.Range("D2").Copy Destination:=Range("D2:D2450")
.Columns("D:D").Value = Columns("D:D").Value
.Columns("D:D").Replace What:="0", Replacement:="", LookAt:=xlWhole, SearchOrder:=xlByRows
End With
Next Ws
End Sub