I was able to compile the sheets in one sheet however I would like to indicate the sheets I want to copy. The source file may have multiple sheets name Delta Prices # therefore I would like to end the loop once it cannot find the sheet's name. Code is:
Option Explicit
Sub CreateDeltaReport()
Dim Newbook As Window
Dim wb As Workbook
Dim wb2 As Workbook
Dim ws As Worksheet
Dim vFile As Variant
Dim wkb As Workbook
Dim wb3 As Workbook
Dim s As Worksheets
Set wb = ThisWorkbook
vFile = Application.GetOpenFilename("All-Files,*.xl**", 1, "Select One File To Open", , False)
If TypeName(vFile) = "Boolean" Then Exit Sub
Workbooks.Open vFile
Set wb2 = ActiveWorkbook
wb2.Activate
Dim j As Integer
Dim h As Integer
On Error Resume Next
Sheets.Add After:=Sheets(Sheets.Count)
ActiveSheet.Name = "Raw Delta"
Sheets("Delta Prices 1").Activate
Range("A1").EntireRow.Select
Selection.Copy Destination:=Sheets("Raw Delta").Range("A1")
h = 1
For Each s In ActiveWorkbook.Sheets
If s.Name <> "Raw Delta" Then
Do
Application.GoTo Sheets("Delta Prices " & h).[a1] ' Sheet name is Delta Prices 1
Selection.CurrentRegion.Select
Selection.Offset(1, 0).Resize(Selection.Rows.Count - 1).Select
Selection.Copy Destination:=Sheets("Raw Delta").Cells(Rows.Count, 1).End(xlUp)(2)
h = h + 1 ' add 1 to h so the sheet name will be "Delta Prices 2 a"
Loop Until s.Name <> ("Delta Prices " & h) ' loop until Sheet name is not "Delta Prices #"
End If
Next
End Sub
Something like this (untested):
Sub CreateDeltaReport()
Dim wb2 As Workbook
Dim vFile As Variant
Dim wkb As Workbook
Dim s As Worksheet
Dim rd As Worksheet, rng As Range
Dim h As Integer
vFile = Application.GetOpenFilename("All-Files,*.xl**", 1, _
"Select One File To Open", , False)
If vFile = False Then Exit Sub
Set wb2 = Workbooks.Open(vFile)
Set rd = wb2.Sheets.Add(After:=wb2.Sheets(wb2.Sheets.Count))
rd.Name = "Raw Delta"
h = 1
Do
Set s = Nothing
On Error Resume Next
Set s = wb2.Worksheets("Delta Prices " & h)
On Error GoTo 0
If s Is Nothing Then
Exit Do
Else
With s.Range("A1").CurrentRegion
.Offset(1, 0).Resize(.Rows.Count - 1, .Columns.Count).Copy _
rd.Cells(Rows.Count, 1).End(xlUp).Offset(1, 0)
End With
End If
h = h + 1
Loop
End Sub
Related
I'm trying to create a VBA code that will only create a ToC for visible sheets. I found some VBA code online and modified it to include Visible = True in the loop, but the hidden sheets are still displaying when I run the macro. I've included the code below and would appreciate any advice on tweaking it to only display visible sheets.
Sub TableOfContents_Create()
'Add a Table of Contents worksheets to easily navigate to any tab
Dim sht As Worksheet
Dim Content_sht As Worksheet
Dim myArray As Variant
Dim x As Long, y As Long
Dim shtName1 As String, shtName2 As String
Dim ContentName As String
'Inputs
ContentName = "Contents"
'Optimize Code
Application.DisplayAlerts = False
Application.ScreenUpdating = False
'Delete Contents Sheet if it already exists
On Error Resume Next
Worksheets("Contents").Activate
On Error GoTo 0
If ActiveSheet.Name = ContentName Then
myAnswer = MsgBox("A worksheet named [" & ContentName & _
"] has already been created, would you like to replace it?", vbYesNo)
'Did user select No or Cancel?
If myAnswer <> vbYes Then GoTo ExitSub
'Delete old Contents Tab
Worksheets(ContentName).Delete
End If
'Create New Contents Sheet
Worksheets.Add Before:=Worksheets(1)
'Set variable to Contents Sheet
Set Content_sht = ActiveSheet
'Format Contents Sheet
With Content_sht
.Name = ContentName
.Range("B1") = "Table of Contents"
.Range("B1").Font.Bold = True
End With
'Create Array list with sheet names (excluding Contents)
ReDim myArray(1 To Worksheets.Count - 1)
For Each sht In ActiveWorkbook.Worksheets
If sht.Name <> ContentName Then
myArray(x + 1) = sht.Name
x = x + 1
End If
Next sht
'Alphabetize Sheet Names in Array List
For x = LBound(myArray) To UBound(myArray)
For y = x To UBound(myArray)
If UCase(myArray(y)) < UCase(myArray(x)) Then
shtName1 = myArray(x)
shtName2 = myArray(y)
myArray(x) = shtName2
myArray(y) = shtName1
End If
Next y
Next x
'Create Table of Contents
For x = LBound(myArray) To UBound(myArray)
Set sht = Worksheets(myArray(x))
sht.Activate
With Content_sht
.Hyperlinks.Add .Cells(x + 2, 3), "", _
SubAddress:="'" & sht.Name & "'!A1", _
TextToDisplay:=sht.Name
.Cells(x + 2, 2).Value = x
End With
Next x
Content_sht.Activate
Content_sht.Columns(3).EntireColumn.AutoFit
ExitSub:
'Optimize Code
Application.DisplayAlerts = True
Application.ScreenUpdating = True
End Sub
The .Visible property of the worksheet has three options:
As you can probably imagine, 0 is converted to False, and 1 or 2 to True. This causes errors, if you try to convert .Visible to a Boolean value.
Thus the idea is to loop only through worksheets, that are xlSheetVisible. Checking simply sht.Visible can lead to an error, if the sheet is xlSheetVeryHidden, because xlSheetVeryHidden is evaluated to True:
Public Sub TestMe()
Dim sht As Worksheet
Set sht = Worksheets(1)
sht.Visible = xlSheetVeryHidden
Debug.Print CBool(sht.Visible) 'prints true
End Sub
Thus use:
If sht.Visible = xlSheetVisible and sht.Name <> ContentName
loop only through visible sheets:
If sht.Name <> ContentName And sht.Visible Then
This question already has answers here:
Copy from one workbook and paste into another
(2 answers)
Closed 5 years ago.
I am trying to copy all data from a workbook on my server and paste the values to B2 in another workbook.
This is what I have so far. It brings me to the workbook 2, but I have to manually select all and copy then paste in workbook 1.
Sub UpdateTSOM()
Application.ScreenUpdating = False
Dim LastRow As Long
Dim StartCell As Range
Set sht = Sheet5
Set reportsheet = Sheet5
Set StartCell = Range("B2")
'Refresh UsedRange
Worksheets("TSOM").UsedRange
'Find Last Row
LastRow = sht.Cells.Find("*", SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row
'Select Range
sht.Range("B2:B" & LastRow).Select
With Range("B2:B" & LastRow)
If MsgBox("Clear all Transmission Stock data?", vbYesNo) = vbYes Then
Worksheets("TSOM").Range("B2:N2000").ClearContents
MsgBox ("Notes:" & vbNewLine & vbNewLine & _ 'This is not needed if I can automate the copy and paste.
"Copy ALL" & vbNewLine & _
"Paste as Values")
End If
End With
Workbooks.Open "P:\ESO\1790-ORL\OUC\_Materials\Stock Status\Transmission Stock Status **-**-**.xlsx"
ThisWorkbook.Activate
reportsheet.Select
Range("B2").Select
whoa: 'If filename changes then open folder
Call Shell("explorer.exe" & " " & "P:\ESO\1790-ORL\OUC\_Materials\Stock Status", vbNormalFocus)
Range("B2").Select
Application.ScreenUpdating = True
End Sub
Thanks
A few guesses as you haven't provided all the details
Sub UpdateTSOM()
Application.ScreenUpdating = False
Dim LastRow As Long
Dim StartCell As Range
Dim sht As Worksheet
Dim wb As Workbook
Set sht = Sheet5
Set StartCell = sht.Range("B2")
'Find Last Row
LastRow = sht.Cells.Find("*", SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row
If MsgBox("Clear all Transmission Stock data?", vbYesNo) = vbYes Then
Worksheets("TSOM").Range("B2:N2000").ClearContents
End If
Set wb = Workbooks.Open("P:\ESO\1790-ORL\OUC\_Materials\Stock Status\Transmission Stock Status **-**-**.xlsx")
wb.Sheets(1).UsedRange.Copy
StartCell.PasteSpecial xlValues
Application.ScreenUpdating = True
End Sub
Avoid SendKeys, and since you are pasting values only, you don't need to use either Copy or Paste/PasteSpecial.
With wsCopyFrom.Range("A1:N3000")
wsCopyTo.Range("B2").Resize(.Rows.Count, .Columns.Count).Value = .Value
End With
Here are several other ways to copy values from one file to another:
Copy from one workbook and paste into another
This is what I got to work. It brings up a select file folder and copies all the data from it into my current workbook. It then names B1 (my header) with the filename without the extension.
Sub UpdateTSOM()
Application.ScreenUpdating = False
Dim vFile As Variant
Dim wbCopyTo As Workbook
Dim wsCopyTo As Worksheet
Dim wbCopyFrom As Workbook
Dim wsCopyFrom As Worksheet
Dim s As String
Set mycell = Worksheets("TSOM").Range("B1")
Set wbCopyTo = ActiveWorkbook
Set wsCopyTo = ActiveSheet
If MsgBox("Update transmission Stock Status data?", vbYesNo) = vbYes Then
Worksheets("TSOM").Range("B2:N3000").ClearContents
Else: Exit Sub
End If
'Locate file to copy data from
vFile = Application.GetOpenFilename("Excel Files (*.xl*)," & _
"*.xl*", 1, "Select Excel File", "Open", False)
'Assign filename to Header
s = Mid(vFile, InStrRev(vFile, "\") + 1)
s = Left$(s, InStrRev(s, ".") - 1)
mycell.Value = s
Set wbCopyFrom = Workbooks.Open(vFile)
Set wsCopyFrom = wbCopyFrom.Worksheets(1)
'Copy Range
wsCopyFrom.Range("A1:N3000").Copy
wsCopyTo.Range("B2").PasteSpecial Paste:=xlPasteValues, _
Operation:=xlNone, SkipBlanks:=False, Transpose:=False
SendKeys "Y"
SendKeys ("{ESC}")
'Close file that was opened
wbCopyFrom.Close SaveChanges:=False
Application.Wait (Now + 0.000005)
Call NoSelect
Exit Sub
End Sub
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
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
I have a main workbook and a sub workbook that macro commands to open
1) Main workbook = Database
Worksheet in Main Workbook = Customer database
Sub workbook = Orders
These two books are open for macro to run.
1) I need to import data Range C:F from Orders to Customer Database B:E if Cell B from Orders contains New Member
2) The worksheet in database already contains data. Hence, I want it to add on to the existing sheet in Database
Please help.
Dim wsSource As Worksheet
Dim wbSource As Workbook
Dim wsTarget As Worksheet
Dim wbTarget As Workbook
Dim findRange As Range
Dim lastline As Integer
Dim file As String
file = "Orders.xlsx"
Set wbSource = ThisWorkbook
Set wsSource = wbSource.Sheets(1)
Set wbTarget = Workbooks.Open(file)
Set wsTarget = wbTarget.Sheets(1)
wsTarget.Activate
Set findRange = wsTarget.Range("C2:F389")
findRange.Replace What:="xxx-string",Replacement:=wsSource.Range("b2:e2").Value, LookAt:=xlPart, SearchOrder:=xlByRows, MatchCase:=False
lastline = wbSource.Sheets(1).Range("X65536").End(xlUp).Row
Dim d As Integer
Dim j As Integer
d = 3
j = 2
For b = 1 To lastline
If wsTarget.Range("B" & j) = "New Member" Then
d = d + 1
wsSource.Range("B" & j).Value = wsTarget.Range("C" & d).Value
wsSource.Range("C" & j).Value = wsTarget.Range("D" & d).Value
wsSource.Range("D" & j).Value = wsTarget.Range("E" & d).Value
wsSource.Range("E" & j).Value = wsTarget.Range("F" & d).Value
End If
j = j + 1
Next b
This answer is based on items 1 and 2 you enumerated above.
I'm not sure what you want to accomplish with the .Replace method so I remove it.
Sub Consolidate()
Dim wsSource As Worksheet
Dim wbSource As Workbook
Dim wsTarget As Worksheet
Dim wbTarget As Workbook
Dim findRange As Range
Dim lastline As Integer
Dim file As Variant '~~> declared as Variant
Set wbSource = Thisworkbook
Set wsSource = wbSource.Sheets(1) '~~>use index only if you have 1 sheet only
file = Application.GetOpenFilename("Excel Files, *.xlsx") '~~> allows you to select the file to load
If file <> False Then
Set wbTarget = Workbooks.Open(file)
Set wsTarget = wbTarget.Sheets(1)
With wsTarget
lastline = .Range("B" & .Rows.Count).End(xlUp).Row
Set findRange = .Range("B1:F" & lastline)
With findRange
.Autofilter 1, "New Member"
.Offset(1,1).Resize(.Rows.Count-1, .Columns.Count-1).SpecialCells(xlCellTypeVisible).Copy _
wsSource.Range("B" & wsSource.Rows.Count).End(xlUp).Offset(1,0)
End With
End With
Else
MsgBox "No file selected. Exiting now." : Exit Sub
End If
wbTarget.Close False
wbSource.Save
End Sub
No need to loop through the whole range.
I used .AutoFilter method instead.
Hope this is close to what you want.