Combine sheets in excel - vba

I have a workbook that has 50 plus sheets in it. What I am looking to do is to combine all the sheets into 1 master sheet with the following criteria:
1. Each sheet in its own column
2. The sheet name as the header of that column
Each sheet has one column (A) with data in it but various amount of rows. There are no headers in the sheets.
From my research I have found that I can combine all the sheets into 1 column, but that does not help.
Any help would be appreciated and thank you

Try this:
Dim J As Integer
On Error Resume Next
Sheets(1).Select
Worksheets.Add
Sheets(1).Name = "Combined"
Sheets(2).Activate
Range("A1").EntireRow.Select
Selection.Copy Destination:=Sheets(1).Range("A1")
For J = 2 To Sheets.Count
Sheets(J).Activate
Range("A1").Select
Selection.CurrentRegion.Select
Selection.Offset(1, 0).Resize(Selection.Rows.Count - 1).Select
Selection.Copy Destination:=Sheets(1).Range("A65536").End(xlUp)(2)
Next
It will help you..

This is a little ugly but it will do what you want. Just change Set targetWS = Sheets("Sheet1") to be the sheet that you are putting all the data.
Sub combineSheets()
Dim sourceWs As Worksheet
Dim targetWs As Worksheet
Dim targetCol As Integer
Dim endRow As Long
'This is the sheet where the data will end up
Set targetWs = Sheets("Sheet1")
'This is the first column to start pasting into
targetCol = 1
'Loop through the worksheets in the workbook
For Each sourceWs In ThisWorkbook.Worksheets
'grab the data from each sheet, bu not the target sheet
If sourceWs.Name <> targetWs.Name Then
'find last row in source sheet
endRow = sourceWs.Range("A999999").End(xlUp).Row()
'paste data and name
targetWs.Range(targetWs.Cells(2, targetCol), targetWs.Cells(endRow, targetCol)) = sourceWs.Range("A1:A" & endRow).Value
targetWs.Cells(1, targetCol).Value = sourceWs.Name
'next column
targetCol = targetCol + 1
End If
Next sourceWs
End Sub

This may help
Option Explicit
Sub CopyRangePaste()
'copies and pastes what is required
Dim wshResult As Worksheet
Dim wsh As Worksheet
Dim msg As String ' alert message
Dim iCounter As Integer
If Worksheets.Count < 2 Then 'if there is only 1 worksheet exits sub
msg = "There is only 1 worksheet." & vbCrLf
msg = msg & "Try again with a different workbook."
MsgBox msg, vbCritical
Exit Sub
End If
Set wshResult = ActiveWorkbook.Sheets.Add
iCounter = 0
For Each wsh In ActiveWorkbook.Worksheets
If wsh.Name <> wshResult.Name Then 'checks if the newly created sheet is not operated on
iCounter = iCounter + 1
wshResult.Cells(1, iCounter) = wsh.Name
wsh.Range(wsh.UsedRange.Find("*").CurrentRegion.Address).Copy _
wshResult.Cells(2, iCounter) 'copies the current region
End If
Next wsh
MsgBox iCounter & " sheets"
End Sub

Related

Include source sheet name to an output sheet

I'm trying to consolidate multiple sheets into one sheet and add a new column for the final "Combined" sheet. The new sheet should have a column named "Source" with the sheet name from where the rows behind it are copied.
Sub Final()
Path = " "
Filename = Dir(Path & "*.csv")
Do While Filename <> ""
Workbooks.Open Filename:=Path & Filename, ReadOnly:=True
For Each Sheet In ActiveWorkbook.Sheets
Sheet.Copy After:=ThisWorkbook.Sheets(1)
Next Sheet
Workbooks(Filename).Close
Filename = Dir()
Loop
Dim J As Integer
On Error Resume Next
Sheets(1).Select
Worksheets.Add
Sheets(1).Name = "Combined"
Sheets(2).Activate
Range("A1").EntireRow.Select
Selection.Copy Destination:=Sheets(1).Range("A1")
For J = 2 To Sheets.Count
Sheets(J).Activate
Range("A1").Select
Selection.CurrentRegion.Select
Selection.Offset(1, 0).Resize(Selection.Rows.Count - 1).Select
Selection.Copy Destination:=Sheets(1).Range("A65536").End(xlUp)(2)
Next
End Sub
thanks in advance for your help guys :)
The code below will copy the sheet's name inside the For J = 2 To ThisWorkbook.Sheets.Count loop to column B (first empty row equivalent to the data exists in Column A).
There are no Select, Selection and ActiveWorkbook, instead there are fully qualified objects like Workbooks, Worksheets and Ranges.
Also, when using On Error Resume Next you should also try to see where the error is coming from, and how to handle it. In your case, it's coming when trying to rename the new created sheet with the name "Combined" , and there is already a worksheet in your workbook with this name. The result is the code skips this line, and the worksheet's names stays wth the default name given by Excel (which is "Sheet" and first available index number).
Code
Option Explicit
Sub Final()
Dim wb As Workbook
Dim Sheet As Worksheet
Dim Path As String, FileName As String
Dim J As Long
Path = " "
FileName = Dir(Path & "*.csv")
Do While FileName <> ""
Set wb = Workbooks.Open(FileName:=Path & FileName, ReadOnly:=True)
For Each Sheet In wb.Sheets
Sheet.Copy after:=ThisWorkbook.Sheets(1)
Next Sheet
wb.Close
Set wb = Nothing
FileName = Dir()
Loop
On Error Resume Next
Set Sheet = Worksheets.Add(after:=Sheets(1))
Sheet.Name = "Combined"
If Err.Number <> 0 Then
Sheet.Name = InputBox("Combined already exists in workbook, select a different name", "Select new created sheet's name")
End If
On Error GoTo 0
Sheets(2).range("A1").EntireRow.Copy Sheets(1).range("A1")
For J = 2 To ThisWorkbook.Sheets.Count
With Sheets(J)
.Range("A1").CurrentRegion.Offset(1, 0).Resize(.Range("A1").CurrentRegion.Rows.Count - 1, .Range("A1").CurrentRegion.Columns.Count).Copy _
Destination:=Sheets(1).Range("A65536").End(xlUp)
Sheets(1).Range("B" & Sheets(1).Cells(Sheets(1).Rows.Count, "A").End(xlUp).Row).Value = .Name '<-- copy the sheet's name to column B
End With
Next J
End Sub
This will create a new sheet or clean the existing one and add 2 columns :
One for the source sheet
One for the source file
Give a try :
Sub Test_Matt()
Dim BasePath As String
Dim FileName As String
Dim tB As Workbook
Dim wB As Workbook
Dim wS As Worksheet
Dim wSCopied As Worksheet
Dim LastRow As Double
Dim ColSrcShtCombi As Integer
Dim ColSrcWbCombi As Integer
Dim wSCombi As Worksheet
Dim NextRowCombi As Double
Dim J As Integer
Set tB = ThisWorkbook
On Error Resume Next
Set wSCombi = tB.Sheets("Combined")
If wSCombi Is Nothing Then
Set wSCombi = tB.Sheets.Add
wSCombi.Name = "Combined"
Else
wSCombi.Cells.Clear
End If
On Error GoTo 0
With wSCombi
'''I don't know which sheet that is your take your headers from,
'''but here is where to define it:
tB.Sheets(2).Range("A1").EntireRow.Copy Destination:=wSCombi.Range("A1")
'''Add "Source"s columns
ColSrcShtCombi = .Cells(1, .Columns.Count).End(xlToLeft).Column + 1
.Cells(1, ColSrcShtCombi).Value = "Source Sheet"
ColSrcWbCombi = ColSrcShtCombi + 1
.Cells(1, ColSrcWbCombi).Value = "Source Workbook"
End With
'''Define here the folder you want to scan:
BasePath = "C:\Example\"
FileName = Dir(BasePath & "*.csv")
Do While FileName <> vbNullString
Set wB = Workbooks.Open(FileName:=BasePath & FileName, ReadOnly:=True)
For Each wS In wS.Sheets
Set wSCopied = wS.Copy(After:=tB.Sheets(tB.Sheets.Count))
'''Find next available row in Combined sheet
NextRowCombi = wSCombi.Range("A" & wSCombi.Rows.Count).End(xlUp).Row + 1
With wSCopied
'''Find the last row of data in that sheet
LastRow = .Range("A" & .Rows.Count).End(xlUp).Row
'''Copy the data in Combined sheet
.Range("A2", .Cells(LastRow, .Cells(1, .Columns.Count).End(xlToLeft).Column)).Copy _
Destination:=wSCombi.Range("A" & NextRowCombi)
'''Put sheet's name and workbook's name in source columns
wSCombi.Range(wSCombi.Cells(NextRowCombi, ColSrcShtCombi), wSCombi.Cells(NextRowCombi + LastRow - 1, ColSrcShtCombi)).Value = wS.Name
wSCombi.Range(wSCombi.Cells(NextRowCombi, ColSrcWbCombi), wSCombi.Cells(NextRowCombi + LastRow - 1, ColSrcWbCombi)).Value = wB.Name
End With 'wSCopied
Next wS
wB.Close
FileName = Dir()
Loop
End Sub

Copying Content from one sheet to another based on a master reference list VBA

I'm trying to format a report and copy the important values onto a blank sheet.
I am using a master list of references to decide which information is important or not. The unique references for each item is store on a Sheet called "Master List" in column B, I want my macro to scan this list and see if it can find a match in the "Raw Data" sheet and copy that matching Row onto the "Report" sheet.
The attempt I have make does all the initial formatting fine, but then stumbles when it hits the first While command. I've tried a couple of different ways to do this and I can't seem to make it work. In the words of Princess Leia, help me Stack Overflow you're my only hope
Dim RD As Worksheet, Report As Worksheet, Masterlist As Worksheet
Dim LSearchRow As Integer
Dim LCopytoRow As Integer
Dim rngFound As Range
Dim SearchItem As String
Set RD = Sheets("Raw Data")
Set Report = Sheets("Report")
Set Masterlist = Sheets("Master List")
LCopytoRow = 1
LSearchRow = 1
RD.Select
Columns("A:A").Select
Selection.Delete Shift:=xlToLeft
Columns("B:D").Select
Selection.Delete Shift:=xlToLeft
Columns("D:Q").Select
Selection.Delete Shift:=xlToLeft
Columns("E:I").Select
Selection.Delete Shift:=xlToLeft
Columns("C:C").Select
Selection.ClearContents
While Len(Range("A" * CStr(LSearchRow)).Value) > 0
SearchItem = Masterlist.Range("B" & k).End(xlUp).Row
If Range("A" & CStr(LSearchRow)).Value = Masterlist.Range("B" & CStr(LSearchRow)).Value Then
Rows(CStr(LSearchRow) & ":" & CStr(LSearchRow)).Select
Selection.Cut
Report.Select
Rows(CStr(LCopytoRow) & ":" & CStr(LCopytoRow)).Select
ActiveSheet.Paste
LCopytoRow = LCopytoRow + 1
RD.Select
End If
LSearchRow = LSearchRow + 1
Wend
Thanks in advance!
Hard to test without sample data, but something like this should work for you:
Sub tgr()
Dim wb As Workbook
Dim wsMstr As Worksheet
Dim wsData As Worksheet
Dim wsRprt As Worksheet
Dim aMasterFilter As Variant
Set wb = ActiveWorkbook
Set wsMstr = wb.Sheets("Master List")
Set wsData = wb.Sheets("Raw Data")
Set wsRprt = wb.Sheets("Report")
wsData.Range("A:A,C:E,H:U,W:AA").EntireColumn.Delete xlToLeft
wsData.Columns("C").EntireColumn.ClearContents
wsData.AutoFilterMode = False
aMasterFilter = Application.Transpose(wsMstr.Range("B1", wsMstr.Cells(wsMstr.Rows.Count, "B").End(xlUp)).Value)
With wsData.Range("A1", wsData.Cells(wsData.Rows.Count, "A").End(xlUp))
.AutoFilter 1, aMasterFilter, xlFilterValues
.EntireRow.Copy wsRprt.Range("A1")
.EntireRow.Delete xlShiftUp
.Parent.AutoFilterMode = False
End With
End Sub

Find word into cell

Excel - VBA
I was wondering how to find a word into a Excel range of rows using VBA. Ex. "word to be found", this is not just the cell value but a word into a string. For instance, the way to find the word "network" into the string "Need help to map network printer".
Sub SearchForSfb()
Dim LSearchRow As Integer
Dim LCopyToRow As Integer
On Error GoTo Err_Execute
'Start search in row 1
LSearchRow = 1
'Start copying data to row 2 in Open (row counter variable)
LCopyToRow = 2
While Len(Range("E" & CStr(LSearchRow)).Value) > 0
'If value in column E = "word to be found", copy entire row to Open
If Range("E" & CStr(LSearchRow)).Value = "word to be found" Then
'Select row in Data to copy
Rows(CStr(LSearchRow) & ":" & CStr(LSearchRow)).Select
Selection.Copy
'Paste row into SFB in next row
Sheets("SFB").Select
Rows(CStr(LCopyToRow) & ":" & CStr(LCopyToRow)).Select
Sheets("SFB").Paste
'Move counter to next row
LCopyToRow = LCopyToRow + 1
'Go back to Data to continue searching
Sheets("Data").Select
End If
LSearchRow = LSearchRow + 1
Wend
'Position on cell A3
Application.CutCopyMode = False
Range("A3").Select
MsgBox "All matching data has been copied."
Exit Sub
Err_Execute:
MsgBox "An error occurred."
End Sub
Use a simple loop
Sub Button1_Click()
Dim ws As Worksheet
Dim sh As Worksheet
Dim lstRw As Long
Dim rng As Range
Dim s As String
Dim c As Range
s = "* network *"
Set ws = Sheets("Data")
Set sh = Sheets("SFB")
With ws
lstRw = .Cells(.Rows.Count, "E").End(xlUp).Row
Set rng = .Range("E2:E" & lstRw)
End With
For Each c In rng.Cells
If c.Value Like s Then
c.EntireRow.Copy sh.Cells(sh.Rows.Count, "A").End(xlUp).Offset(1)
End If
Next c
End Sub
Or you can use a filter macro
Sub FiltExample()
Dim ws As Worksheet, sh As Worksheet
Dim rws As Long, rng As Range
Set ws = Sheets("Data")
Set sh = Sheets("SFB")
Application.ScreenUpdating = 0
With ws
rws = .Cells(.Rows.Count, "E").End(xlUp).Row
.Range("E:E").AutoFilter Field:=1, Criteria1:="=*network*"
Set rng = .Range("A2:Z" & rws).SpecialCells(xlCellTypeVisible)
rng.EntireRow.Copy sh.Cells(sh.Rows.Count, "A").End(xlUp).Offset(1)
.AutoFilterMode = False
End With
End Sub

VBA Copy non-blank cells in EACH worksheet to existing worksheet

I don't even know where to start so I don't have any example code. I am thinking that I need a nested loop but that is what throws me off. I look forward to learning from everyone.
Here is what I'd like to do:
Begin with the worksheet named "John" and loop through each worksheet to the right.
On each worksheet, if a cell in column L is not blank, copy cell F and cell L for that row.
Append all of the copied cells to the worksheet "Notes". Paste the data from F on each sheet to column A and paste the corresponding data from L in column B. Add the copied data from each worksheet to the end of the data in "Notes".
I really appreciate any help, thanks!!
UPDATE
Based on Alter's great help and suggestions, this is what I have and it works perfectly. Thanks Alter!
Sub test()
Dim ws As Worksheet
Dim notes_ws As Worksheet
Dim row
Dim lastrow
Dim notes_nextrow
'find the worksheet called notes
For Each ws In Worksheets
If ws.Name = "Notes" Then
Set notes_ws = ws
End If
Next ws
'get the nextrow to print to
notes_nextrow = notes_ws.Range("A" & Rows.Count).End(xlUp).row + 1
'loop through other worksheets
For Each ws In Worksheets
'ignore the notes worksheet
If ws.Name <> "Notes" And ws.Index > Sheets("John").Index Then
'find lastrow
lastrow = ws.Range("L" & Rows.Count).End(xlUp).row
For row = 1 To lastrow
'if the cell is not empty
If IsEmpty(ws.Range("L" & row)) = False Then
notes_ws.Range("A" & notes_nextrow).Value = ws.Range("F" & row).Value
notes_ws.Range("B" & notes_nextrow).Value = ws.Range("L" & row).Value
notes_nextrow = notes_nextrow + 1
End If
Next row
End If
Next ws
End Sub
Nested loop indeed, you can use the code below as a basis for what you want to do
Public Sub test()
Dim ws As Worksheet
Dim notes_ws As Worksheet
Dim row
Dim lastrow
Dim notes_nextrow
'find the worksheet called notes
For Each ws In Worksheets
If ws.name = "Notes" Then
Set notes_ws = ws
End If
Next ws
'get the nextrow to print to
notes_nextrow = notes_ws.Range("A" & Rows.Count).End(xlUp).row + 1
'loop through other worksheets
For Each ws In Worksheets
'ignore the notes worksheet
If ws.name <> "Notes" Then
'find lastrow
lastrow = ws.Range("L" & Rows.Count).End(xlUp).row
For row = 1 To lastrow
'if the cell is not empty
If IsEmpty(ws.Range("L" & row)) = False Then
notes_ws.Range("A" & notes_nextrow).Value = ws.Range("L" & row).Value
notes_nextrow = notes_nextrow + 1
End If
Next row
End If
Next ws
End Sub

VBA to combine multiple worksheets into one and insert a row between each worksheet

I need to consolidate multiple worksheets in to one worksheet while having a space left between each tab of consolidated information. Can anyone help with this? Below is the code I have but I'm missing something:
Sub CopyWorksheets()
Dim wrk As Workbook
Dim sht As Worksheet
Dim trg As Worksheet
Dim rng As Range
Dim colCount As Integer
Set wrk = ActiveWorkbook 'Working in active workbook
For Each sht In wrk.Worksheets
If sht.Name = "Master" Then
MsgBox "There is a worksheet called as 'Master'." & vbCrLf & _
"Please remove or rename this worksheet since 'Master' would be" & _
"the name of the result worksheet of this process.", _
vbOKOnly + vbExclamation, "Error"
Exit Sub
End If
Next sht
'We don't want screen updating
Application.ScreenUpdating = False
'Add new worksheet as the last worksheet
Set trg = wrk.Worksheets.Add(After:=wrk.Worksheets(wrk.Worksheets.Count))
'Rename the new worksheet
trg.Name = "Master"
'Get column headers from the first worksheet
'Column count first
Set sht = wrk.Worksheets(1)
colCount = sht.Cells(1, 255).End(xlToLeft).Column
'Now retrieve headers, no copy&paste needed
With trg.Cells(1, 1).Resize(1, colCount)
.Value = sht.Cells(1, 1).Resize(1, colCount).Value
'Set font as bold
.Font.Bold = True
End With
'We can start loop
For Each sht In wrk.Worksheets
'If worksheet in loop is the last one, stop execution (it is Master worksheet)
If sht.Index = wrk.Worksheets.Count Then
Exit For
End If
'Data range in worksheet - starts from second row as
'first rows are the header rows in all worksheets
Set rng = sht.Range(sht.Cells(2, 1), sht.Cells(65536, 1).End(xlUp).Resize(, colCount))
'Put data into the Master worksheet
trg.Cells(65536, 1).End(xlUp).Offset(1).Resize(rng.Rows.Count, _
rng.Columns.Count).Value = rng.Value
'move cursor to bottom on active range and insert row
Range("A65536").End(xlUp).Offset(1, 0).Select
Selection.Offset(1, 0).Select
Next sht
'Fit the columns in Master worksheet
trg.Columns.AutoFit
'Screen updating should be activated
Application.ScreenUpdating = True
End Sub
Maybe this is what you need:
For Each sht In wrk.Worksheets
If sht.Index = wrk.Worksheets.Count Then Exit For
Set rng = sht.Range(sht.Cells(2, 1), _
sht.Cells(rows.count, 1).End(xlUp).Resize(, colCount))
'Put data into the Master worksheet (skip one empty row)
trg.Cells(rows.count, 1).End(xlUp).Offset(2).Resize(rng.Rows.Count, _
rng.Columns.Count).Value = rng.Value
Next sht