Summary sheet created from multiple worksheets using a dynamic range - vba

I have a 176 worksheets in a workbook, that all have the same format/structure, but are a difference size in row length.
I want to copy the data that is held in range A10:V(X) where X is a calculable number. This data will be pasted underneath each other, in columns B:W of the main sheet "RDBMergeSheet" and the name of the sheet that each row came from will be pasted into Column A of RDBMergeSheet so it can be seen which rows came from which sheets
X = (The lowest used row number in column J) - 3
If it makes it easier, another way to calculate X is find the row number in column A that contains the word "total" and subtract 1 from it.
The following link contains an example of such a sheet, with sanitised data.
https://imgur.com/a/emlZj
The code I've got so far, with help, is:
Sub ImportData()
Dim x As Long
Dim LR As Long
Dim wks As Worksheet
With Application
.ScreenUpdating = False
.EnableEvents = False
.DisplayAlerts = False
End With
Set wks = Sheets("RDBMergeSheet"): If Not wks Is Nothing Then wks.Delete
Set wks = Worksheets.Add(after:=Worksheets(Sheets.Count))
wks.Name = "RDBMergeSheet"
For x = 1 To Worksheets.Count - 1
LR = Application.Max(1, Sheets(x).Cells(Rows.Count, 10).End(xlUp).Row - 3)
With wks.Cells(Rows.Count, 1)
.Offset(1, 1).Resize(LR, 22).Value = .Cells(1, 10).Resize(LR, 22).Value
.Offset(1).Resize(LR - 9).Value = Sheets(x).Name
End With
Next x
wks.Select
With Application
.ScreenUpdating = False
.EnableEvents = False
.DisplayAlerts = False
End With
Set wks = Nothing
End Sub
This errors out with a 1004: Application defined or object defined error on line
.Offset(1, 1).Resize(LR, 22).Value = .Cells(1, 10).Resize(LR, 22).Value
If anyone has any ideas on either how to resolve this I would be extremely grateful.

Please give this a try and tweak it as per your requirement to make sure the correct data is copied starting from the correct row on destination sheet.
Sub ImportData()
Dim LR As Long, dLR As Long, i As Long
Dim wks As Worksheet
With Application
.Calculation = xlCalculationManual
.ScreenUpdating = False
.EnableEvents = False
.DisplayAlerts = False
End With
On Error Resume Next
Set wks = Sheets("RDBMergeSheet")
wks.Cells.Clear
On Error GoTo 0
If wks Is Nothing Then
Set wks = Worksheets.Add(after:=Worksheets(Sheets.Count))
wks.Name = "RDBMergeSheet"
End If
For i = 1 To Worksheets.Count - 1
If Worksheets(i).Name <> wks.Name Then
LR = Application.Max(1, Sheets(i).Cells(Rows.Count, 10).End(xlUp).Row - 3)
If LR > 9 Then
If wks.Range("B1").Value = "" Then
dLR = 1
Else
dLR = wks.UsedRange.Rows.Count + 1
End If
wks.Range("B" & dLR & ":X" & LR - 9).Value = Worksheets(i).Range("B10:X" & LR).Value
wks.Range("A" & dLR).Value = Worksheets(i).Name
End If
End If
Next i
On Error Resume Next
wks.Select
dLR = wks.UsedRange.Rows.Count
wks.Range("A1:A" & dLR).SpecialCells(xlCellTypeBlanks).Formula = "=R[-1]C"
wks.Range("A1:A" & dLR).Value = wks.Range("A1:A" & dLR).Value
With Application
.Calculation = xlCalculationAutomatic
.ScreenUpdating = True
.EnableEvents = True
.DisplayAlerts = True
End With
Set wks = Nothing
End Sub

Related

Editing code to stop user from jumping from sheet to sheet

I have some code that copies data from one sheet on to another and then deletes empty rows. The code kind of works, but i sends the user from sheet to sheet while doing it. I am still new to VBA and im now sure how to achieve the result without using the select property. What I need to code to do, is move data from one sheet to another and delete empty rows when a button is clicked. I want the user to stay on the front page while the code executes. My code is below:
Sub MarkSold()
Dim LSearchRow As Integer
Dim LCopyToRow As Integer
On Error GoTo Err_Execute
'Start search in row 6
LSearchRow = 6
'Start copying data to row 6 in Sheet3 (row counter variable)
LCopyToRow = 6
While Len(Sheets("on stock").Range("B" & CStr(LSearchRow)).Value) > 0
'If value in column B = "D5", copy entire row to Sheet3
If Sheets("On stock").Range("B" & CStr(LSearchRow)).Value = Sheets("Data Entry").Range("D5") Then
'Select row in Sheet1 to copy
Sheets("On stock").Select
Rows(CStr(LSearchRow) & ":" & CStr(LSearchRow)).Select
Selection.Cut
'Paste row into Sheet2 in next row
Sheets("Turbines sold").Select
Rows(CStr(LCopyToRow) & ":" & CStr(LCopyToRow)).Select
ActiveSheet.Paste
'Move counter to next row
LCopyToRow = LCopyToRow + 1
'Go back to Sheet1 to continue searching
Sheets("On stock").Select
End If
LSearchRow = LSearchRow + 1
Wend
Dim sh As Worksheet
Dim lr As Long, i As Long
Set sh = Sheets("On stock")
With Application
.ScreenUpdating = False
.DisplayStatusBar = False
.Calculation = xlCalculationManual
.EnableEvents = False
lr = sh.Cells(Rows.Count, 1).End(xlUp).Row
For i = lr To 6 Step -1
If WorksheetFunction.CountA(Rows(i)) = 0 Then
Rows(i).EntireRow.Delete
End If
Next i
.EnableEvents = True
.Calculation = xlCalculationAutomatic
.DisplayStatusBar = True
.ScreenUpdating = True
End With
Call setupDV
'Position on cell A3
Application.CutCopyMode = False
Sheets("Data Entry").Range("A1").Select
MsgBox "Now marked as sold!"
Exit Sub
Err_Execute:
'MsgBox "An error occurred."
End Sub
Any help is appreciated!
Just remove the .Select statement from your code and set refer your code directly to each sheet. Just like The code below:
Sub MarkSold()
Dim LSearchRow As Integer
Dim LCopyToRow As Integer
Set stock = Sheets("On stock")
Set tSold = Sheets("Turbines sold")
Set dEntry = Sheets("Data Entry")
On Error GoTo Err_Execute
'Start search in row 6
LSearchRow = 6
'Start copying data to row 6 in Sheet3 (row counter variable)
LCopyToRow = 6
While Len(Sheets("on stock").Range("B" & CStr(LSearchRow)).Value) > 0
'If value in column B = "D5", copy entire row to Sheet3
If Sheets("On stock").Range("B" & CStr(LSearchRow)).Value = Sheets("Data Entry").Range("D5") Then
'Select row in Sheet1 to copy
Sheets("On stock").Rows(CStr(LSearchRow) & ":" & CStr(LSearchRow)).Cut
'Paste row into Sheet2 in next row
Sheets("Turbines sold").Rows(CStr(LCopyToRow) & ":" & CStr(LCopyToRow)).Paste
'Move counter to next row
LCopyToRow = LCopyToRow + 1
End If
LSearchRow = LSearchRow + 1
Wend
Dim sh As Worksheet
Dim lr As Long, i As Long
Set sh = Sheets("On stock")
With Application
.ScreenUpdating = False
.DisplayStatusBar = False
.Calculation = xlCalculationManual
.EnableEvents = False
lr = sh.Cells(Rows.Count, 1).End(xlUp).Row
For i = lr To 6 Step -1
If WorksheetFunction.CountA(Rows(i)) = 0 Then
Rows(i).EntireRow.Delete
End If
Next i
.EnableEvents = True
.Calculation = xlCalculationAutomatic
.DisplayStatusBar = True
.ScreenUpdating = True
End With
Call setupDV
Application.CutCopyMode = False
MsgBox "Now marked as sold!"
Exit Sub
Err_Execute:
'MsgBox "An error occurred."
End Sub
I've cleaned up your code a little and commented on it, so you can follow the reasoning for the changes:
Sub MarkSold()
Dim sh As Worksheet
Dim lr As Long
Dim i As Long
Dim LSearchRow As Long
Dim LCopyToRow As Long
'the variables above ought to be declared as Long instead of Integer, as there
'are more cells in Excel than there are Integer values
On Error GoTo Err_Execute
'Start search in row 6
LSearchRow = 6
'Start copying data to row 6 in Sheet3 (row counter variable)
LCopyToRow = 6
While Len(Sheets("On stock").Range("B" & LSearchRow).Value) > 0
'If value in column B = "D5", copy entire row to Sheet3
If Sheets("On stock").Range("B" & LSearchRow).Value = Sheets("Data Entry").Range("D5") Then
'Select row in Sheet1 to copy
Sheets("On stock").Rows(LSearchRow).Cut
'Paste row into Sheet2 in next row
Sheets("Turbines sold").Rows(LCopyToRow).Paste
'Move counter to next row
LCopyToRow = LCopyToRow + 1
'Go back to Sheet1 to continue searching
End If
LSearchRow = LSearchRow + 1
Wend
Set sh = Sheets("On stock")
With Application
.ScreenUpdating = False
.DisplayStatusBar = False
.Calculation = xlCalculationManual
.EnableEvents = False
lr = sh.Cells(Rows.Count, 1).End(xlUp).Row
For i = lr To 6 Step -1
If WorksheetFunction.CountA(Rows(i)) = 0 Then
Rows(i).EntireRow.Delete
End If
Next i
.EnableEvents = True
.Calculation = xlCalculationAutomatic
.DisplayStatusBar = True
.ScreenUpdating = True
End With
Call setupDV
'Position on cell A3
Application.CutCopyMode = False
Sheets("Data Entry").Range("A1").Select
'Do you really need the select command above?
MsgBox "Now marked as sold!"
Exit Sub
Err_Execute:
'MsgBox "An error occurred."
End Sub

VBA, Copy rows from multple Worksheets to a master sheet

I have a macro that does a calculation for all sheets in a workbook, I need to copy these results(which are located in the last row of each sheet, but each row may be different for each sheet) to a master sheet(as it needs to be done for multiple files), could anyone help alter my macro to do this or even make a new one?
If needed here is my macro:
Sub Calculationallsheetsv2()
'Calculation all sheets, even when there is only headers
Dim xrng As Range, lrw As Long, lrng As Range, i As Long
Dim LstCo As Long, ws As Worksheet
With Application
.ScreenUpdating = False
.Calculation = xlCalculationManual
End With
For Each ws In ActiveWorkbook.Worksheets
With ws
If Not Application.WorksheetFunction.CountA(.Cells) = 0 Then
LstCo = .Cells.Find("*", , xlValues, xlWhole, xlByColumns, xlPrevious, False).Column
For i = 1 To LstCo
With .Columns(i)
.TextToColumns Destination:=.Cells(1, 1), DataType:=xlDelimited, TrailingMinusNumbers:=True
End With
Next
lrw = .Columns("A:Y").Find("*", , xlValues, , xlRows, xlPrevious).row
If lrw = 1 Then lrw = 2
Set lrng = .Range("A" & lrw + 2)
With .Range("A2:A" & lrw)
lrng.Formula = "=COUNTA(" & .Address(0, 0) & ")/ROWS(" & .Address(0, 0) & ")"
End With
Set xrng = .Range(lrng, .Cells(lrng.row, LstCo))
lrng.AutoFill xrng, Type:=xlFillDefault
xrng.Style = "Percent"
End If
End With
Next
With Application
.ScreenUpdating = True
.Calculation = xlCalculationAutomatic
Application.CalculateFull
End With
End Sub
Below is the code to accomplish the task you have described. I put some comment, so you can understand what is going on. If you have any further questions regarding this code, ask in comment.
NOTE. There is one external function used in the code below so you need to include it in your code as well, otherwise it will not compile. Here is the code of this function - Function to find the last non-empty row in a given worksheet.
Sub Calculationallsheetsv2()
'Calculation all sheets, even when there is only headers
Const SUMMARY_SHEET_NAME As String = "Summary"
'-----------------------------------------
Dim wkb As Excel.Workbook
Dim wks As Excel.Worksheet
Dim wksSummary As Excel.Worksheet
Dim arrRow As Variant
Dim lastRow As Long
'-----------------------------------------
With Application
.ScreenUpdating = False
.Calculation = xlCalculationManual
End With
Set wkb = Excel.ActiveWorkbook
'Create [Summary] worksheet. -----------------------------------------------------
On Error Resume Next
Set wksSummary = wkb.Worksheets(SUMMARY_SHEET_NAME)
On Error GoTo 0
If wksSummary Is Nothing Then
Set wksSummary = wkb.Worksheets.Add
wksSummary.Name = SUMMARY_SHEET_NAME
End If
'---------------------------------------------------------------------------------
'Iterate through all the worksheets in the workbook [wkb].
For Each wks In wkb.Worksheets
'Check the name of currently checked worksheet to exclude [Summary] worksheet
'from this process.
If wks.Name <> SUMMARY_SHEET_NAME Then
'Check if there are any non-empty cells in this worksheet.
If Application.WorksheetFunction.CountA(wks.Cells) Then
'Find the index number of the last empty row.
lastRow = lastNonEmptyRow(wks)
'Copy the content of this row into array.
arrRow = wks.Rows(lastRow).EntireRow
'Paste the content of [arrRow] array into the first empty
'row of the [Summary] worksheet.
With wksSummary
.Rows(lastNonEmptyRow(wksSummary) + 1).EntireRow = arrRow
End With
End If
End If
Next wks
'Restore screen updating and automatic calculation
With Application
.ScreenUpdating = True
.Calculation = xlCalculationAutomatic
Call .CalculateFull
End With
End Sub
EDIT
If you want to put the result into a new workbook instead of a new worksheet within the same workbook you need to replace this block of code:
'Create [Summary] worksheet. -----------------------------------------------------
On Error Resume Next
Set wksSummary = wkb.Worksheets(SUMMARY_SHEET_NAME)
On Error GoTo 0
If wksSummary Is Nothing Then
Set wksSummary = wkb.Worksheets.Add
wksSummary.Name = SUMMARY_SHEET_NAME
End If
'---------------------------------------------------------------------------------
with this one:
'Create [Summary] worksheet. -----------------------------------------------------
Dim wkbSummary As Excel.Workbook
Set wkbSummary = Excel.Workbooks.Add
Set wksSummary = wkbSummary.Worksheets.Add
wksSummary.Name = SUMMARY_SHEET_NAME
'---------------------------------------------------------------------------------

Excel Add Sheet or Overwrite if Exists

In excel I have a macro that converts all of columns of an active sheet into an new sheet called "MasterList"
My problem is when I rerun that macro I get an error saying "That name is already taken." Try a different one.
I need my macro to overwrite MaterList sheet if it already exists.
Here is my code:
Sub ToArrayAndBack()
Dim arr As Variant, lLoop1 As Long, lLoop2 As Long
Dim arr2 As Variant, lIndex As Long
'turn off updates to speed up code execution
With Application
.ScreenUpdating = False
.EnableEvents = False
.Calculation = xlCalculationManual
.DisplayAlerts = False
End With
ReDim arr2(ActiveSheet.UsedRange.Cells.Count - ActiveSheet.UsedRange.SpecialCells(xlCellTypeBlanks).Count)
arr = ActiveSheet.UsedRange.Value
For lLoop1 = LBound(arr, 1) To UBound(arr, 1)
For lLoop2 = LBound(arr, 2) To UBound(arr, 2)
If Len(Trim(arr(lLoop1, lLoop2))) > 0 Then
arr2(lIndex) = arr(lLoop1, lLoop2)
lIndex = lIndex + 1
End If
Next
Next
Sheets.Add.Name = "MasterList"
Range("A1").Resize(, lIndex + 1).Value = arr2
Range("A1").Resize(, lIndex + 1).Copy
Range("A2").Resize(lIndex + 1).PasteSpecial Transpose:=True
Rows(1).Delete
With Application
.ScreenUpdating = True
.EnableEvents = True
.Calculation = xlCalculationAutomatic
.DisplayAlerts = True
End With
End Sub
You can put the sheet creation between on error resume and on error goto 0. The other solution is to loop through the workbook sheets collection and check if a sheet with that name exists.
Solution 1:
On Error Resume Next
Sheets.Add.Name = "MasterList"
On Error GoTo 0
Solution 2:
Dim ws As Worksheet
Dim found As Boolean
found = False
For Each ws In ThisWorkbook.Sheets
If ws.Name = "MasterList" Then
found = True
Exit For
EndIf
Next
If Not found Then
Sheets.Add.Name = "MasterList"
EndIf
To avoid relying on the fact that MasterList is active:
Set ws = ThisWorkbook.Sheets("MasterList")
With ws
.Range("A1").Resize(, lIndex + 1).Value = arr2
.Range("A1").Resize(, lIndex + 1).Copy
.Range("A2").Resize(lIndex + 1).PasteSpecial Transpose:=True
.Rows(1).Delete
End With

Excel VBA copying rows using autofilter

Looking to copy rows from all sheets apart from my active sheet that meet a certain criteria in column J using VBA.
Not experienced in writing code in VBA so I have tried to frankenstein together the necessary parts from looking through other questions and answers;
below is the code I have written so far;
Sub CommandButton1_Click()
Dim lngLastRow As Long
Dim ws As Worksheet
Dim r As Long, c As Long
Dim wsRow As Long
Set Controlled = Sheets("Controlled") ' Set This to the Sheet name you want all Ok's going to
Worksheets("Controlled").Activate
r = ActiveSheet.Cells(Rows.Count, 2).End(x1up).Row
c = ActiveSheet.Cells(1, Columns.Count).End(x1ToLeft).Column
Range("J").AutoFilter
For Each ws In Worksheets
If ws.Name <> "Controlled" Then
ws.Activate
wsRow = ActiveSheet.Cells(Rows.Count, 2).End(x1up).Row + 1
Range("A" & r).AutoFilter Field:=10, Criteria1:="Y"
.Copy Controlled.Range("A3" & wsRow)
End If
Next ws
End If
Application.ScreenUpdating = True
Application.EnableEvents = True
Application.Calculation = xlCalculationAutomatic
End Sub
Where Controlled is the sheet I want the data to appear in from the other sheets, and all other sheets are searched to see if their column J meets the criteria="Y"
I won't need to copy over formatting as all Sheets will have the formatting exactly the same and if possible I want the rows that are copied over to start at row 3
Try this:
Option Explicit
Sub ConsolidateY()
Dim ws As Worksheet, wsCtrl As Worksheet
Dim lrow As Long, rng As Range
Set wsCtrl = Thisworkbook.Sheets("Controlled")
With Application
.ScreenUpdating = False
.DisplayAlerts = False
End With
For Each ws In Thisworkbook.Worksheets
If ws.Name = "Controlled" Then GoTo nextsheet
With ws
lrow = .Range("J" & .Rows.Count).End(xlUp).Row
.AutoFilterMode = False
Set rng = .Range("J1:J" & lrow).Find(what:="Y", after:=.Range("J" & lrow))
If rng Is Nothing Then GoTo nextsheet
.Range("J1:J" & lrow).AutoFilter Field:=1, Criteria1:="Y"
.Range("J1:J" & lrow).Offset(1,0).SpecialCells(xlCellTypeVisible).EntireRow.Copy
wsCtrl.Range("A" & wsCtrl.Rows.Count).End(xlUp).Offset(1,0).PasteSpecial xlPasteValues
.AutoFilterMode = False
Application.CutCopyMode = False
End With
nextsheet:
Next
With Application
.ScreenUpdating = True
.DisplayAlerts = True
End With
End Sub
I think this covers everything or most of your requirement.
Not tested though so I leave it to you.
If you come across with problems, let me know.

VBA Excel Code Running Much slower in 2010 than 2007

I have some code that runs fine in Excel 2007 but when used in Excel 2010 takes about ten times longer to run and causes the whole taskbar/other programs to be unresponsive.
I don't believe hardware is the problem because the computer running Excel 2007 is a Pentium 4 with 2 gigs of ram, while the computer running 2010 is an i7 with 8 gigs of ram.
Here is the code itself:
Sub Macro6()
With Application
.ScreenUpdating = False 'Prevent screen flickering
.Calculation = xlCalculationManual 'Preventing calculation
.DisplayAlerts = False 'Turn OFF alerts
.EnableEvents = False 'Prevent All Events
End With
Dim i As Integer
Dim j As Integer
Dim Anc As String
Dim MSA As String
j = 1
Do
i = 0
MSA = ActiveCell
Selection.Copy
Sheets("Sheet1").Select
ActiveCell.Offset(0, -2).Select
ActiveSheet.Paste
ActiveCell.Offset(0, 2).Select
Sheets("wip").Select
Do
i = i + 1
ActiveCell.Offset(0, 1).Select
Anc = ActiveCell.Offset(-j, 0)
Selection.Copy
Sheets("Sheet1").Select
ActiveCell.Offset(0, -1) = Anc
ActiveCell.Offset(0, -2) = MSA
ActiveSheet.Paste
ActiveCell.Offset(1, 0).Select
Sheets("wip").Select
Loop Until IsEmpty(ActiveCell.Offset(0, 1))
j = j + 1
ActiveCell.Offset(1, -i).Select
Loop Until IsEmpty(ActiveCell)
'Speeding Up VBA Code
With Application
.ScreenUpdating = True 'Prevent screen flickering
.Calculation = xlAutomatic 'Preventing calculation
.DisplayAlerts = True 'Turn OFF alerts
.EnableEvents = True 'Prevent All Events
End With
End Sub
The code does what I want it to, but I am concerned as to why in 2010 there is such a difference in running time?
Is this what you are trying to do?
Option Explicit
Sub Sample()
Dim ws1 As Worksheet, ws2 As Worksheet
Dim i As Long, j As Long, k As Long, lRow As Long, lCol As Long
On Error GoTo Whoa
With Application
.ScreenUpdating = False
.Calculation = xlCalculationManual
.EnableEvents = False
End With
'~~> Setting the worksheets to work with
Set ws1 = Sheets("wip"): Set ws2 = Sheets("Sheet1")
'~~> Setting the start cell in "Sheet1"
k = 3
With ws1
'~~> Get the last row in Col A of "wip"
lRow = .Range("A" & .Rows.Count).End(xlUp).Row
'~~> Get the last column in row 3 of "wip"
lCol = .Cells(3, .Columns.Count).End(xlToLeft).Column
'~~> Looping through rows in Col A in "wip"
For i = 3 To lRow
'~~> Looping through columns in the relevant row in "wip"
For j = 3 To lCol + 1
'~~> Writing output directly in "Sheet1"
ws2.Cells(k, 1).Value = ws1.Cells(i, 1).Value
ws2.Cells(k, 3).Value = ws1.Cells(i, 1).Offset(, j - 2).Value
k = k + 1
Next j
Next i
End With
LetsContinue:
With Application
.ScreenUpdating = False
.Calculation = xlCalculationManual
.EnableEvents = False
End With
Exit Sub
Whoa:
MsgBox Err.Description
Resume LetsContinue
End Sub