Include source sheet name to an output sheet - vba

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

Related

Copy one cell and paste down a column

Been trying to figure out how to copy a cell from worksheet A and paste it down a column in Worksheet B until it matches the same amount of rows as an adjacent column. Take the following screenshot for example. How would I properly accomplish this in VBA? Been trying to figure this out for a while now. All I've been able to do is copy the cell and paste it adjacent to the last cell in the adjacent column instead of down the entire column. The worksheet I'm copying data from is pictured below.
Copy From SpreadSheet down below
Paste to SpreadSheet down below
Current Code
Sub pullSecEquipment()
Dim path As String
Dim ThisWB As String
Dim wbDest As Workbook
Dim shtDest As Worksheet
Dim shtPull As Worksheet
Dim Filename As String
Dim Wkb As Workbook
Dim CopyRng As Range, DestRng As Range
Dim lRow As Integer
Dim destLRow As Integer
Dim Lastrow As Long
Dim FirstRow As Long
Dim UpdateDate As String
ThisWB = ActiveWorkbook.Name
Dim selectedFolder
With Application.FileDialog(msoFileDialogFolderPicker)
.Show
selectedFolder = .SelectedItems(1) & "\"
End With
path = selectedFolder
Application.EnableEvents = False
Application.ScreenUpdating = False
Set shtDest = Workbooks("GPnewchapterTEST2.xlsm").Worksheets("START")
'clear content of destination table
shtDest.Rows("8:" & Rows.Count).ClearContents
Filename = Dir(path & "\*.xls*", vbNormal)
If Len(Filename) = 0 Then Exit Sub
Do Until Filename = vbNullString
Set Wkb = Workbooks.Open(Filename:=path & "\" & Filename)
'MsgBox Filename
'''''
'SEC
'''''
If InStr(Filename, "Equipment") <> 0 Then
Dim range1 As Range
Set range1 = Range("E:K")
'For Each Wkb In Application.Workbooks
'For Each shtDest In Wkb.Worksheets
'Set shtPull = Wkb.Sheets(1)
'If shtPull.Name Like "*-*" Then
'last row
destLRow = Wkb.Sheets(1).Cells.Find(what:="*", SearchOrder:=xlRows, SearchDirection:=xlPrevious, LookIn:=xlValues).Row
'1st row
lRow = Wkb.Sheets(1).Cells.Find(what:="EQUIPMENT DESCRIPTION", SearchOrder:=xlRows, SearchDirection:=xlPrevious, LookIn:=xlValues).Row + 1
'STHours
Dim i As Integer
For i = lRow To destLRow
Set CopyRng = Wkb.Sheets(1).Range(Cells(i, 5).Address, Cells(i, 11).Address)
Set DestRng = shtDest.Range("O" & shtDest.Cells(Rows.Count, "O").End(xlUp).Row + 1)
CopyRng.Copy
DestRng.PasteSpecial Transpose:=True
Application.CutCopyMode = False 'Clear Clipboard
Set CopyRng = Wkb.Sheets(1).Range(Cells(i, 1).Address, Cells(i, 1).Address)
Set DestRng = shtDest.Range("C" & shtDest.Cells(Rows.Count, "O").End(xlDown).Row)
CopyRng.Copy
DestRng.PasteSpecial Transpose:=True
Application.CutCopyMode = False 'Clear Clipboard
Set CopyRng = Wkb.Sheets(1).Range(Cells(i, 3).Address, Cells(i, 3).Address)
Set DestRng = shtDest.Range("S" & shtDest.Cells(Rows.Count, "O").End(xlUp).Row)
CopyRng.Copy
DestRng.PasteSpecial Transpose:=True
Application.CutCopyMode = False 'Clear Clipboard
i = i + 2
Next i
'Dim cell As Integer
'Dim empname As String
'destLRow = 8 '' find out how to find first available row
'For cell = 2 To lRow
'empname = Wkb.Sheets(1).Cells(cell, 3).Value & " " & Wkb.Sheets(1).Cells(cell, 4).Value
' shtDest.Cells(8, 5).Value = empname
'shtDest.Cells(8, 1).Value = "Service Electric"
'Next cell
' Wkb.Close Save = False
End If
'End If
Filename = Dir()
Loop
MsgBox "Done!"
End Sub
if you want to do in VBA and want to copy one value in "ALL" column
Cells(1,1).Copy Columns(1)

VBA codes could not run in marco enabled file type

Sorry that I am new to VBA, thanks to all the experts here I am able to copy some of the codes and modify them to suit my needs. Basically, they are just a couple of command buttons which carry out various functions. It work out fine in my excel 2010. However, when I try to save the file in my another computer with Excel 2007 (Confirmed that vba is running), a message popup saying
"The following Features cannot be saved in a macro-free workbooks:
VB Project
To save a file with these features, click no, and then choose a macro-enabled file type..."
Even I clicked no and then save it as xlsm. When I opened the file, all the vba codes are disabled. I just wonder whether it is due to any line of the following codes that could not be run in excel 2007. Many thanks for your help!
Apologies for the codes being a mess.
Private Sub CommandButton1_Click()
' Defines variables
Dim Wb1 As Workbook, Wb2 As Workbook
' Disables screen updating to reduce flicker
Application.ScreenUpdating = False
' Sets Wb1 as the current (destination) workbook
Set Wb1 = ThisWorkbook
' Sets Wb2 as the defined workbook and opens it - Update filepath / filename as required
Set Wb2 = Workbooks.Open("\\new_admin\MASTER_FILE.xlsx")
' Sets LastRow as the first blank row of Wb1 Sheet1 based on column A (requires at least header if document is otherwise blank)
lastrow = Sheets(1).Cells(Rows.count, "A").End(xlUp).Row + 1
' With workbook 2
With Wb2
' Activate it
.Activate
' Activate the desired sheet - Currently set to sheet 1, change the number accordingly
.Sheets(1).Activate
' Copy the used range of the active sheet
.ActiveSheet.UsedRange.Copy
End With
' Then with workbook 1
With Wb1.Sheets(1)
' Activate it
.Activate
' Select the first blank row based on column A
.Range("A1").Select
' Paste the copied data
.Paste
End With
' Close workbook 2
Wb2.Close
' Re-enables screen updating
Application.ScreenUpdating = False
End Sub
Private Sub CommandButton2_Click()
' Defines variables
Dim Wb1 As Workbook, Wb2 As Workbook
' Disables screen updating to reduce flicker
Application.ScreenUpdating = False
' Sets Wb1 as the current (destination) workbook
Set Wb1 = ThisWorkbook
' Sets Wb2 as the defined workbook and opens it - Update filepath / filename as required
Set Wb2 = Workbooks.Open("C:\Users\admin\Desktop\Accom_Master_File.xlsx")
' Sets LastRow as the first blank row of Wb1 Sheet1 based on column A (requires at least header if document is otherwise blank)
lastrow = Sheets(2).Cells(Rows.count, "A").End(xlUp).Row + 1
' With workbook 2
With Wb2
' Activate it
.Activate
' Activate the desired sheet - Currently set to sheet 1, change the number accordingly
.Sheets(1).Activate
' Copy the used range of the active sheet
.ActiveSheet.UsedRange.Copy
End With
' Then with workbook 1
With Wb1.Sheets(2)
' Activate it
.Activate
' Select the first blank row based on column A
.Range("A1").Select
' Paste the copied data
.Paste
End With
' Close workbook 2
Wb2.Close
' Re-enables screen updating
Application.ScreenUpdating = False
Dim wkb As Workbook
Set wkb = ThisWorkbook
wkb.Sheets("Sheet1").Activate
End Sub
Private Sub CommandButton3_Click()
Range("B2").CurrentRegion.Select
Selection.Sort Key1:=Range("B2"), Order1:=xlAscending, Header:=xlGuess, _
OrderCustom:=1, MatchCase:=False, Orientation:=xlTopToBottom, _
DataOption1:=xlSortNormal
ThisWorkbook.Sheets("Sheet2").Range("B:C").Delete xlUp
ThisWorkbook.Sheets("Sheet2").Columns(2).Copy
ThisWorkbook.Sheets("Sheet2").Columns(1).Insert
ThisWorkbook.Sheets("Sheet2").Columns(3).Delete
End Sub
Private Sub CommandButton4_Click()
Dim dicKey As String
Dim dicValues As String
Dim dic
Dim data
Dim x(1 To 35000, 1 To 24)
Dim j As Long
Dim count As Long
Dim lastrow As Long
lastrow = Cells(Rows.count, 1).End(xlUp).Row
data = Range("A2:X" & lastrow) ' load data into variable
With CreateObject("scripting.dictionary")
For i = 1 To UBound(data)
If .Exists(data(i, 2)) = True Then 'test to see if the key exists
x(count, 3) = x(count, 3) & ";" & data(i, 3)
x(count, 8) = x(count, 8) & ";" & data(i, 8)
x(count, 9) = x(count, 9) & ";" & data(i, 9)
x(count, 10) = x(count, 10) & ";" & data(i, 10)
x(count, 21) = x(count, 21) & ";" & data(i, 21)
Else
count = count + 1
dicKey = data(i, 2) 'set the key
dicValues = data(i, 2) 'set the value for data to be stored
.Add dicKey, dicValues
For j = 1 To 24
x(count, j) = data(i, j)
Next j
End If
Next i
End With
Rows("2:300").EntireRow.Delete
Sheets("Sheet1").Cells(2, 1).Resize(count - 1, 24).Value = x
End Sub
Private Sub CommandButton5_Click()
If ActiveSheet.AutoFilterMode Then Selection.AutoFilter
ActiveCell.CurrentRegion.Select
With Selection
.AutoFilter
.AutoFilter Field:=1, Criteria1:="ACTIVE"
.AutoFilter Field:=5, Criteria1:="NUMBERS"
.Offset(1, 0).Select
End With
Dim ws As Worksheet
Dim rVis As Range
Application.ScreenUpdating = False
For Each ws In Worksheets
Do Until ws.Columns("A").SpecialCells(xlVisible).count = ws.Rows.count
Set rVis = ws.Columns("A").SpecialCells(xlVisible)
If rVis.Row = 1 Then
ws.Rows(rVis.Areas(1).Rows.count + 1 & ":" & rVis.Areas(2).Row - 1).Delete
Else
ws.Rows("1:" & rVis.Row - 1).Delete
End If
Loop
Next ws
Application.ScreenUpdating = True
Dim LR As Long
LR = Cells(Rows.count, 1).End(xlUp).Row
Rows(LR).Copy
Rows(LR + 2).Insert
End Sub
Private Sub CommandButton6_Click()
Columns("A").Delete
Dim lastrow As Long
lastrow = Range("A2").End(xlDown).Row
Range("X2:X" & lastrow).FormulaR1C1 = "=IF(RC[+1]=""PAYING"", VLOOKUP(RC[-23],'Sheet2'!R1C1:R20000C8,8,0),""PENDING"")"
Range("Y2:Y" & lastrow).FormulaR1C1 = "=IFERROR(VLOOKUP(RC[-24],'Sheet2'!R1C1:R20000C8,2,0), ""PENDING"")"
Range("Z2:Z" & lastrow).FormulaR1C1 = "=(LEN(RC[-24])-LEN(SUBSTITUTE(RC[-24], "";"", """"))+1)*1200"
Range("AA2:AA" & lastrow).FormulaR1C1 = "=VLOOKUP(RC[-26],'Sheet3'!R2C2:R220C4,2,0)"
Range("AB2:AB" & lastrow).FormulaR1C1 = "=VLOOKUP(RC[-27],'Sheet3'!R2C2:R220C4,3,0)"
Range("AC2:AC" & lastrow).FormulaR1C1 = "=IFERROR(VLOOKUP(RC[-28],'Sheet4'!R1C1:R30C3,2,0),"""")"
Range("AD2:AD" & lastrow).FormulaR1C1 = "=IFERROR(VLOOKUP(RC[-29],'Sheet4'!R1C4:R30C6,2,0),"""")"
Columns("X:AD").EntireColumn.AutoFit
Sheets(1).Columns(24).NumberFormat = "#"
Sheets(1).Columns(25).NumberFormat = "#"
Sheets(1).Columns(29).NumberFormat = "#"
Sheets(1).Columns(30).NumberFormat = "#"
End Sub
Private Sub CommandButton7_Click()
Sheet1.Cells.Clear
End Sub
When something like this happens to me I just start up a new workbook and save explicitly in .xls or .xlsm format and then copy and paste my module or class code into new modules and classes in the new workbook. -- cannot post comments yet so if this doesn't help i shall delete this answer.

Merging different worksheet into one sheet (only specified rows)

I Have multiple worksheets (like 24 in number!). I would like to merge it into single sheet. All the worksheets have similar structure with header.
Glitch: At the end of every worksheet there is one or two rows with data summary
I would like to omit those line and have continues data of all worksheets.
Here is a piece of code which I used to merge it. But it made multiple sheets in single excel file. Is it possible to add some code within this piece of code.
Thanks in advance!
Sub GetSheets()
Path = "C:\path"
Filename = Dir(Path & "*.XLSX")
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
End Sub
What does following code do:
- Code will copy data from all the sheets of all .xlsx files in the specified folder assuming all files have same structure
- Data is copied to sheet name Output of active file
- Last row of each sheet is not copied assuming it contains data summary
- Header will be copied from the first copied sheet
- Code will not add sheets to current file
Sub GetSheets()
Dim path As String, fileName As String
Dim lastRow As Long, rowCntr As Long, lastColumn As Long
Dim outputWS As Worksheet
Application.ScreenUpdating = False
Application.Calculation = xlCalculationManual
'this is the sheet where all the data will be displyed
Set outputWS = ThisWorkbook.Sheets("Output")
rowCntr = 1
path = "C:\path" & "\"
fileName = Dir(path & "*.XLSX")
Do While fileName <> ""
Workbooks.Open fileName:=path & fileName, ReadOnly:=True
For Each ws In ActiveWorkbook.Sheets
If rowCntr = 1 Then
'get column count
lastColumn = ws.Cells(1, Columns.Count).End(xlToLeft).Column
'copy header
Range(outputWS.Cells(1, 1), outputWS.Cells(1, lastColumn)).Value = Range(ws.Cells(1, 1), ws.Cells(1, lastColumn)).Value
rowCntr = rowCntr + 1
End If
'get last row with data of each sheet
lastRow = ws.Cells(Rows.Count, "A").End(xlUp).Row
'copy data from each sheet to Output sheet
Range(outputWS.Cells(rowCntr, 1), outputWS.Cells(rowCntr + lastRow - 3, lastColumn)).Value = Range(ws.Cells(2, 1), ws.Cells(lastRow - 1, lastColumn)).Value
rowCntr = rowCntr + lastRow - 2
Next ws
Workbooks(fileName).Close
fileName = Dir()
Loop
Application.ScreenUpdating = True
Application.Calculation = xlCalculationAutomatic
End Sub
Following code may be useful for combining sheets.
This will ask to browse for file to combine. Then it will combine all sheets into one sheet named "Combine"
Sub Combine()
Dim openfile As String
MsgBox "Pls select Input file", vbOKOnly
openfile = Application.GetOpenFilename(FileFilter:="Excel Files (*.xlsx), *.xlsx", Title:="Select File To Be Opened")
Workbooks.OpenText (openfile)
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
Sheets(1).Select
End Sub
Once you've got them all into your active workbook you could do an additional step to put them on the same sheet.
Not knowing the layout of your data its difficult but if I assume there's always something in A1 and it's all in a large block then you could loop through the sheets and copy something like:
Dim i as integer
For i = 1 to ActiveWorkbook.Sheets.Count
Sheets(i).Range("A1").CurrentRegion.Copy
'Paste it into the sheet here below what's already there
Next i

How to read headers from closed file and paste it in new sheet as column using VBA

I have 10+ files in a folder. i wants to copy all files headers to new sheet as a column. i am able to do this . But i wants to copy file name and sheet name also i tried but not getting data.
plz see the attchments and below code.
Code:
Public Sub CommandButton1_Click()
'DECLARE AND SET VARIABLES
Dim wbk As Workbook
Dim Filename As String
Dim Path As String
Dim mainwb As Workbook
Dim ws As Worksheet
Dim search_result As Range 'range search result
Dim blank_cell As Long
Dim wb As Workbook
Workbooks("abc.xlsm").Activate
input_directory = Sheets("SystemConfiguration").Range("B2").Value & "\"
Filename = Dir(input_directory & "*.xls")
'--------------------------------------------
'OPEN EXCEL FILES
Do While Len(Filename) > 0 'IF NEXT FILE EXISTS THEN
Set wbk = Workbooks.Open(input_directory & Filename)
Set wbk = ActiveWorkbook
Filename = ActiveWorkbook.Name
Variable = ActiveSheet.Name
ActiveSheet.UsedRange.Rows(1).Copy
Workbooks("newfile.xlsm").Activate
'ActiveWorkbook.ActiveSheet
Set wb = ActiveWorkbook
Set ws = wb.Sheets("Sheet1")
For Each cell In ws.Columns(7).Cells
If IsEmpty(cell) = True Then cell.Select: Exit For
Next cell
Selection.PasteSpecial Paste:=xlPasteValues, Transpose:=True
wbk.Close savechanges:=False
Filename = Dir
Loop
End Sub
this output is getting Mr.Mrig
Expecting this output
Mr.Mrig this is my code after changes
Public Sub CommandButton1_Click()
Dim wbk As Workbook
Dim Filename As String
Dim Path As String
Dim mainwb As Workbook
Dim ws As Worksheet
Dim wb As Workbook
Dim variable As String
Dim rowCount As Long
Dim add As Range
Workbooks("abc.xlsm").Activate
input_directory = Sheets("SystemConfiguration").Range("B2").Value & "\"
Filename = Dir(input_directory & "*.xls")
Do While Len(Filename) > 0 'IF NEXT FILE EXISTS THEN
Set wbk = Workbooks.Open(input_directory & Filename)
Set wbk = ActiveWorkbook
Filename = ActiveWorkbook.Name
variable = ActiveSheet.Name
ActiveSheet.UsedRange.Rows(1).Copy
Workbooks("abc.xlsm").Activate
Set wb = ActiveWorkbook
Set ws = wb.Sheets("Sheet1")
For Each cell In ws.Columns(12).Cells
If IsEmpty(cell) = True Then cell.Select: Exit For
Next cell
Set add = Selection
Selection.Offset(0, 2).PasteSpecial Paste:=xlPasteValues, Transpose:=True
rowCount = Selection.Rows.Count
Range(add, add.Offset(rowCount - 1, 0)).Value = Filename
Range(add.Offset(0, 1), add.Offset(rowCount - 1, 1)).Value = variable
wbk.Close savechanges:=False
Filename = Dir
Loop
End Sub
Made some changes in your code.
Replace following line
Selection.PasteSpecial Paste:=xlPasteValues, Transpose:=True
to
Selection.Value = Filename '-->display file name in Column G(7)
Selection.Offset(0, 1).Value = variable '-->display sheet name in Column H(8)
Selection.Offset(0, 2).PasteSpecial Paste:=xlPasteValues, Transpose:=True '-->display header in Column I(9)
EDIT :
________________________________________________________________________________
Dim rowCount As Long
Dim add As Range
Set add = Selection
Selection.Offset(0, 2).PasteSpecial Paste:=xlPasteValues, Transpose:=True
rowCount = Selection.Rows.Count
Range(add, add.Offset(rowCount - 1, 0)).Value = Filename
Range(add.Offset(0, 1), add.Offset(rowCount - 1, 1)).Value = variable

Combine sheets in excel

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