Merge specific sheets by adding the sheet name as the first column - vba

I have quite a number of sheets whose names end in _A or _B.
I would like to merge all sheets ending in _A or _B under one another. They have the same number of columns, but different number of rows. However, when merging, I want the sheetname to be repeated all the way down the last row of that sheet in the merged sheet. Result:
I want the results to be saved in the same workbook but in a sheet called "merged".
here is the example sheet if you would like to work on.
what I have tried:
Sub Merge_into_One()
Dim ws As Worksheet
Dim TargetRow As Long
Application.Calculation = xlCalculationManual
Application.ScreenUpdating = False
TargetRow = 1
For Each ws In ActiveWorkbook.Sheets
With ws
If .Name Like "*" & strSearch & "_A" Or _
.Name Like "*" & strSearch & "_B" Then
.Range("A1:C99").Copy
With Worksheets("Merged").Cells(TargetRow, 1)
.PasteSpecial Paste:=xlPasteValuesAndNumberFormats
End With
TargetRow = TargetRow + 99
End If
End With
Next ws
Application.CutCopyMode = False
Application.ScreenUpdating = True
End Sub
But here, i am taking 99 rows, supposing that my rows will not exceed this number. However, I want to take exactly the same number of rows that appear in each sheet, not more not less. And here I cannot put the name of the sheet in the first column and repeat it until the last hit of the same sheet.

Not tested. EDIT: Oops I forgot a few things it seems.
dim RowsToMerge as integer
dim RowsPresent
dim RangeToMerge as range
For i = 1 To ActiveWorkbook.Worksheets.Count
If Instr(Worksheets(i).Name, "ABC") <> 0 Then
Set ws = Worksheets(i)
RowsToMerge = ws.Cells(Rows.Count, "A").End(xlUp).Row
RowsPresent = Sheets("Merged").Cells(Rows.Count, "A").End(xlUp).Row
Set RangeToMerge = ws.Range("A1:C" & RowsToMerge)
ws.RangeToMerge.Copy destination:=Worksheets("Merged").Range("B" & RowsPresent + 1)
Worksheets("Merged").Range("A" & RowsPresent + 1) = ws.Name
End If
Next

Related

copying from one sheet to another

I am trying to copy my data depending on the column value. If column R has invalid, then it should copy all information from sheet1 to sheet2.
I have below code running. Due to some reason it does not copy the last two rows of my sheet1.
I have 551 rows in sheet1 , and I have the 551 row column R as invalid. 'It checks only till 548 rows and skips the last row without moving them.
Could someone help me to fix this issue
Sub Tab()
Dim cell As Range
Dim nextrow As Long
Dim a As Double
Application.ScreenUpdating = False
' get the count of rows in column r
a = Sheets("sheet1").Cells(Rows.count, "R").End(xlUp).Row
MsgBox (a)
For Each cell In Sheets("sheet1").Range("R5:R" & a)
' if the cell in column R has invalid, then copy the entire row to another sheet
If cell.Value = "Invalid" Then
nextrow = Application.WorksheetFunction.CountA(Sheets("sheet2").Range("R:R"))
Rows(cell.Row).Copy Destination:=Sheets("sheet2").Range("A" & nextrow + 1)
End If
Next
Application.ScreenUpdating = True
End Sub
Instead of
Rows(cell.Row).Copy Destination:=Sheets("sheet2").Range("A" & nextrow + 1)
try
Sheets("sheet1").Rows(cell.Row).Copy Destination:=Sheets("sheet2").Range("A" & nextrow + 1)
Your code can be written as
Sub Demo()
Dim cell As Range
Dim nextrow As Long, a as Long
Dim srcSht As Worksheet, destSht As Worksheet
Application.ScreenUpdating = False
Set srcSht = ThisWorkbook.Sheets("Sheet3")
Set destSht = ThisWorkbook.Sheets("Sheet6")
nextrow = Application.WorksheetFunction.CountA(destSht.Range("R:R"))
With srcSht
a = .Cells(.Rows.Count, "R").End(xlUp).Row
MsgBox a
For Each cell In .Range("R5:R" & a)
' if the cell in column R has invalid, then copy the entire row to another sheet
If cell.Value = "Invalid" Then
.Rows(cell.Row).Copy Destination:=destSht.Range("A" & nextrow + 1)
nextrow = nextrow + 1
End If
Next
End With
Application.ScreenUpdating = True
End Sub
Also instead of pasting data row by row you can also use UNION.
I will not go into the part on the variables and methodology (everyone has their way of scripting). I will respond based on your base code above, hopefully it is clear for your understanding.
Sub Tab()
Dim cell As Range
Dim nextrow As Long
Dim a As Double
Application.ScreenUpdating = False
' get the count of rows in column r
a = Sheets("sheet1").Cells(Rows.count, "R").End(xlUp).Row
MsgBox (a)
'This is assuming that you will always populate starting from the first row Range("A1") in Sheet2
nextrow = 1
For Each cell In Sheets("sheet1").Range("R5:R" & a)
' if the cell in column R has invalid, then copy the entire row to another sheet
If cell.Value = "Invalid" Then
'Use the EntireRow function to copy the whole row to the Sheet2.
'During the next iteration, it will +1 to nextrow, so the next record will be copied to Range("A2"), next Range("A3") and so forth.
cell.EntireRow.Copy Destination:=Sheets("Sheet2").Range("a" & nextrow)
nextrow = nextrow + 1
End If
Next
Application.ScreenUpdating = True
End Sub

Excel VBA - Run through multiple row, if a row is blank, enter a section of headers

I'm writing a macro to sort through a large file of data at work. I've inserted a blank row at the top of different section of data. I want my code to realize when a row is blank in column C, then fill in a set of headers in that row. It should then continue to find the next blank in column C. This should continue until my code finds 2 consecutive blanks, which signals the end of my data.
Currently, my code inserts the desired headers, but only in the first row of my worksheet. I believe that I need to change the loop contained inside my "Do... Loop Until" function. I just can't seem to get the correct code to achieve my desired results.
I've included a screencapture of roughly what my spreadsheet will look like.
Any help or advice is greatly appreciated.
This is the code I have so far:
Sub AddHeaders()
'Add headers below each section title
Dim Headers() As Variant
Dim ws As Worksheet
Dim wb As Workbook
Dim LastRow As Long, Row As Long
Application.ScreenUpdating = False 'turn this off for the macro to run a
little faster
Set wb = ActiveWorkbook
LastRow = Cells(Rows.Count, 1).End(xlUp).Row
ActiveCell = Cells(1, 3)
Headers() = Array("Item", "Configuration", "Drawing/Document Number",
"Title", "ECN", "Date", "Revisions")
' Set Do loop to stop when two consecutive empty cells are reached.
Do
For Row = 1 To LastRow 'Add a loop to go through the cells in each row?
If IsEmpty(ActiveCell) = True Then 'If row is empty, then go in and add headers
For i = LBound(Headers()) To UBound(Headers())
Cells(Row, 1 + i).Value = Headers(i)
Next i
Rows(Row).Font.Bold = True
'Loop here
End If
Next Row
ActiveCell = ActiveCell.Offset(1, 0)
Loop Until IsEmpty(ActiveCell) And IsEmpty(ActiveCell.Offset(1, 0))
Application.ScreenUpdating = True 'turn it back on
MsgBox ("Done!")
Is this what you are looking for?
I removed the activecell stuff and used range instead.
Also removed the do loop and only use the for loop.
I think it works but Not sure. It does not look like you have on your picture but I keept your text code.
Sub AddHeaders()
'Add headers below each section title
Dim Headers() As Variant
Dim ws As Worksheet
Dim wb As Workbook
Dim LastRow As Long, Row As Long
Application.ScreenUpdating = False 'turn this off for the macro to run a
Set wb = ActiveWorkbook
LastRow = Cells(Rows.Count, 3).End(xlUp).Row
ActiveCell = Cells(1, 3)
Headers() = Array("Item", "Configuration", "Drawing/Document Number", "Title", "ECN", "Date", "Revisions")
' Set Do loop to stop when two consecutive empty cells are reached.
For Row = 1 To LastRow 'Add a loop to go through the cells in each row?
If Range("C" & Row).Value = "" Then 'If row is empty, then go in and add headers
For i = LBound(Headers()) To UBound(Headers())
Cells(Row, 1 + i).Value = Headers(i)
Next i
Rows(Row).Font.Bold = True
'Loop here
End If
Next Row
Application.ScreenUpdating = True 'turn it back on
MsgBox ("Done!")
End Sub
Edit; Include image of output of above code.
Here's how I would do it:
Sub AddHeaders()
Dim nRow As Integer
nRow = 1
Do Until Range("C" & nRow) = "" And Range("C" & nRow + 1) = ""
If Range("C" & nRow) = "" Then
Range("A" & nRow & ":D" & nRow) = "Header"
End If
nRow = nRow + 1
Loop
End Sub

Print same worksheet multiple times in one job

I am attempting to print the same worksheet multiple times as one print job. I have a worksheet that has a table with columns ID, FirstName, LastName, and Age. I have another worksheet that acts like a form.
Users select an ID and the rest of the columns get automatically populated (First Name, LastName, and Age).
I already have code that once the user selects which ID they want from a dropdown, the sheet updates with the information for that ID automatically.
I am trying to add a macro that will print the same worksheet for each ID. So if I had 2 id's for example:
the code will use my existing macro to update the worksheet with ID1
print the worksheet
use my code to update the worksheet with ID2
print the worksheet
In the end though, I would like to have one print job that has both sheets in it.
I already know I could use the below code to print the worksheets separate:
Sub PrintForms()
dim myID as integer
'myID gets the last ID numer
myID = sheets("CondForm").Range("A1").Value
for i = 1 to myID
'this just takes the ID number from i and updates the worksheet with the data for that id
call misc.UpdateSheet(i)
Sheets("Data Form").PrintOut
Next i
End Sub
But I need all of the prints to come out as one print job so that if they chose pdf for example it gets printed as one pdf document and not hundreds.
I also found this method that will print an array of sheets, but it still doesn't let me update the sheet between prints.
Sub PrintArray()
Dim SheetsToPrint As String
Dim MyArr() As String
SheetsToPrint = "Data Table,Data Form"
'Split the string into an array
MyArr = Split(SheetsToPrint, ",")
ThisWorkbook.Worksheets(MyArr).PrintOut
End Sub
try this - adjust the original data - I assumed different records every 20 rows in this code.
Sub testit()
Dim ws As Worksheet, lastRow As Long, originalWS As Worksheet
Dim originalRowCounter As Long, wsRowCounter As Long, numberRecords As Long
Dim i As Long
Application.ScreenUpdating = False
Set originalWS = ActiveSheet
Set ws = Sheets.Add
originalRowCounter = 1
wsRowCounter = 1
originalWS.Activate
' Assume every 20 rows on originalWS has idividual record - adjust this accordingly
lastRow = originalWS.Cells.Find(What:="*", After:=[A1], SearchDirection:=xlPrevious).Row + 1
numberRecords = lastRow / 20
For i = 1 To numberRecords
originalWS.Range("A" & originalRowCounter & ":K" & (originalRowCounter + 19)).Select
Selection.Copy
ws.Activate
ws.Range("A" & wsRowCounter).Activate
ActiveSheet.Paste
originalRowCounter = originalRowCounter + 20
wsRowCounter = wsRowCounter + 20
ws.Rows(wsRowCounter).PageBreak = xlPageBreakManual
originalWS.Activate
Next i
Application.PrintCommunication = False
With ws.PageSetup
.FitToPagesWide = 1
.FitToPagesTall = False
End With
Application.PrintCommunication = True
ws.PrintOut
Application.DisplayAlerts = False
ws.Delete
Application.DisplayAlerts = True
Application.ScreenUpdating = True
Set originalWS = Nothing
Set ws = Nothing
End Sub

Copy/Paste multiple rows in VBA

I am attempting to do a simple copy row, paste row within a workbook. I've searched threads and tried changing my code multiple times to no avail.
The one that comes closest to working is this but it only copies a single instance of matching criteria.
I am trying to create a loop that will copy all of the rows that has a match in one of the columns.
So, if 8 columns, each row with matching value in column 7 should copy to a named sheet.
Sub test()
Set MR = Sheets("Main").Range("H1:H1000")
Dim WOLastRow As Long, Iter As Long
For Each cell In MR
If cell.Value = "X" Then
cell.EntireRow.Copy
Sheets("X").Range("A" & Rows.Count).End(xlUp).PasteSpecial
End If
If cell.Value = "Y" Then
cell.EntireRow.Copy
Sheets("Y").Range("A" & Rows.Count).End(xlUp).PasteSpecial
End If
If cell.Value = "Z" Then
cell.EntireRow.Copy
Sheets("Z").Range("A" & Rows.Count).End(xlUp).PasteSpecial
End If
If cell.Value = "AB" Then
cell.EntireRow.Copy
Sheets("AB").Range("A" & Rows.Count).End(xlUp).PasteSpecial
End If
Application.CutCopyMode = False
Next
End Sub
I like this because I need to target multiple destination sheets with different criteria but I need all rows that match criteria to copy over.
EDITED CODE IN RESPONSE TO NEW REQUEST:
The code below will copy all of the rows in Sheet Main and paste them into the corresponding worksheets based on the value in Column 7.
Do note: If there is a value in Column 7 that does NOT match to an existing sheet name, the code will throw an error. Modify the code to handle that exception.
Let me know of any additional needed help.
Sub CopyStuff()
Dim wsMain As Worksheet
Dim wsPaste As Worksheet
Dim rngCopy As Range
Dim nLastRow As Long
Dim nPasteRow As Long
Dim rngCell As Range
Dim ws As Worksheet
Const COLUMN_TO_LOOP As Integer = 7
Application.ScreenUpdating = False
Set wsMain = Worksheets("Main")
nLastRow = wsMain.Cells(Rows.Count, 1).End(xlUp).Row
Set rngCopy = wsMain.Range("A2:H" & nLastRow)
For Each ws In ActiveWorkbook.Worksheets
If UCase(ws.Name) = "MAIN" Then
'Do Nothing for now
Else
Intersect(ws.UsedRange, ws.Columns("A:H")).ClearContents
End If
Next ws
For Each rngCell In Intersect(rngCopy, Columns(COLUMN_TO_LOOP))
On Error Resume Next
Set wsPaste = Worksheets(rngCell.Value)
On Error GoTo 0
If wsPaste Is Nothing Then
MsgBox ("Sheet name: " & rngCell.Value & " does not exist")
Else
nPasteRow = wsPaste.Cells(Rows.Count, 1).End(xlUp).Row + 1
wsMain.Range("A" & rngCell.Row).Resize(, 8).Copy wsPaste.Cells(nPasteRow, 1)
End If
Set wsPaste = Nothing
Next rngCell
Application.ScreenUpdating = True
End Sub
Your current code is pasting to the same row in each sheet over and over, to the last row with a value in column A. Range("A" & Rows.Count).End(xlUp) says, roughly "go to the very bottom of the spreadsheet in column A, and then jump up from there to the next lowest cell in column A with contents," which gets you back to the same cell each time.
Instead, you could use lines of the pattern:
Sheets("X").Range("A" & Sheets("X").UsedRange.Rows.Count + 1).PasteSpecial
Where UsedRange is a range containing all of the cells on the sheet with data in them. The + 1 puts you on the following row.
You could make this a little prettier using With:
With Sheets("X")
.Range("A" & .UsedRange.Rows.Count + 1).PasteSpecial
End With

create a macro to copy multiple rows of data from one sheet to another based on a criteria

I am trying to write a macro that will let me copy a range of data from one sheet to another sheet based on a criteria in the column before the column to be copied.
Column B is the criteria column. If there is a 1 in any row in this column then columns C thru AN will be copied from that row where there is a 1 and be pasted into another sheet starting at the top of that sheet.
I have the following code. It locates the first row that satisfies the criteria and copies this row to the second sheet, however the code does not loop thru to find other rows that satisfy the criteria. How can I adjust the code to loop and copy each instance where the criteria is satisfied?
Sub testIt()
Dim i As Integer
Application.ScreenUpdating = False
Sheets("DataDump").Activate
For i = 2 To Range("B2").End(xlDown).Row()
If Range("B" & i).Value = 1 Then
Range("C" & i, "AN" & i).Copy
Sheets("PriceData").Activate
ActiveSheet.Range("B2", "AM2").Select
ActiveSheet.Paste
End If
Next i
Application.ScreenUpdating = True
End Sub
Sub testIt()
Dim i As Long, shtSrc As Worksheet, rngDest As Range
Application.ScreenUpdating = False
Set shtSrc = Sheets("DataDump")
Set rngDest = Sheets("PriceData").Cells(Rows.Count, 2).End(xlUp).Offset(1, 0)
For i = 2 To shtSrc.Range("B2").End(xlDown).Row
If shtSrc.Range("B" & i).Value = 1 Then
shtSrc.Range("C" & i & ":AN" & i).Copy rngDest
Set rngDest = rngDest.Offset(1, 0)
End If
Next i
Application.ScreenUpdating = True
End Sub