I have worksheets I want to copy to a new, temporary workbook -- without saving it.
Worksheet.Copy copies the worksheet to a new, unnamed'ish (Book1, Book2, Book3, etc) workbook. I want all sheets to be copied to the same workbook.
For all worksheets after the first, I have tried using Worksheet.Copy After:=xlWb.Sheets(1), but I do not know how to reference the newly created workbook when setting the xlWb workbook-object. I keep receiving
run-time error 9, 'Subscript out of range'.
Dim xlApp As Excel.Application
Dim xlWb As Excel.Workbook
Dim xlWbOld As String
Dim xlWs As Excel.Worksheet
Dim xlWbNew As Excel.Workbook
Dim xlWsOld As Excel.Worksheet
Dim xlRng As Excel.Range
Dim xlRngOld As Excel.Range
xlWbOld = ActiveWorkbook.Name
Set xlApp = New Excel.Application
xlApp.Visible = True '*** Quite Important to set Excel.Visible,_
'Otherwise user wouldn't see the application's running _
'even though it would run as background
xlApp.Application.ScreenUpdating = False
Set xlWb = xlApp.Workbooks.Add 'Create a new Workbook
Set xlWs = xlWb.Worksheets.Add
And this is where the worksheets should be copied:
Select Case strRptType
Case "DAILY"
xlWs.Name = "1-Daily Price"
'Check the last column and the last row
lLastRow = oBasic.GetLast(, "DailyRpt", False, "A")
iLastCol = oBasic.GetLast(, "DailyRpt", True, 4)
Set xlRngOld = wksDailyRpt.Range(wksDailyRpt.Cells(4, 1), wksDailyRpt.Cells(lLastRow, iLastCol))
Application.ScreenUpdating = True
xlRngOld.Copy
Set xlRng = xlWs.Cells(1, 1)
xlRng.PasteSpecial Paste:=xlPasteValues
xlWs.Columns.AutoFit
For Each xlWsOld In ActiveWorkbook.Worksheets
If xlWsOld.Name = "ForwardPrices" Or xlWsOld.Name = "ForwardVolatilities" _
Or xlWsOld.Name = "ForwardReturns" Or xlWsOld.Name = "ForwardCorrelations" Then
Sheets(xlWsOld.Name).Copy After:=Workbooks(xlWb).Sheets(1)
End If
Next xlWsOld
End Select
This little macro goes through all the sheets of all the open workbooks, and copies them after the current sheet.
Sub GatherAllSheets()
Dim Wb As Workbook, Sh As Worksheet
For Each Wb In Workbooks
If Not Wb Is ThisWorkbook Then
For Each Sh In Wb.Worksheets
Sh.Copy after:=ActiveSheet
Next Sh
End If
Next Wb
End Sub
Is this what you need?
Or you need to copy the content of the sheets on the same sheet?
I solved it with the following:
For Each xlWsOld In ActiveWorkbook.Worksheets
If xlWsOld.Name = "ForwardPrices" Or xlWsOld.Name = "ForwardVolatilities" _
Or xlWsOld.Name = "ForwardReturns" Or xlWsOld.Name = "ForwardCorrelations" Then
Set xlRngOld = Nothing
Set xlWsForwards = xlWb.Worksheets.Add
lLastRow = oBasic.GetLast(, xlWsOld.Name, False, "A")
iLastCol = oBasic.GetLast(, xlWsOld.Name, True, 1)
Set xlRngOld = xlWsOld.Range(xlWsOld.Cells(1, 1), xlWsOld.Cells(lLastRow, iLastCol))
xlWsForwards.Name = xlWsOld.Name
xlRngOld.Copy
Set xlRngForwards = xlWsForwards.Cells(1, 1)
xlRngForwards.PasteSpecial Paste:=xlPasteValues
xlWsForwards.Columns.AutoFit
xlWsForwards.Cells(1, 1).Select
Set xlWsForwards = Nothing
End If
Next xlWsOld
skip creating the new workbook, and copy all the sheets in one go.
xlWbOld.Sheets(Array("ForwardPrices", "ForwardVolatilities", "ForwardReturns", "ForwardCorrelations")).Copy
Set xlWb = ActiveWorkbook
this way copying creates the new workbook which becomes ActiveWorkbook. then you can assign it to a workbook object, and reference it by that name later on
Related
I have around 500 workbooks that I have managed to import into a master workbook into separate tabs. I want to be able to append data from each of the separate workbooks into the correct tab of the master workbook on a weekly basis.
Below is the code I have so far:
Sub ImportData()
Dim Path As String, Filename As String
Dim wb As Workbook
Dim Sht As Worksheet, ShtDest As Worksheet
Path = "C:\Users\J\Currencies\"
Filename = Dir(Path & "*.xlsx*")
Application.ScreenUpdating = False
Application.DisplayAlerts = False
Do While Filename <> ""
Set wb = Workbooks.Open(Filename:=Path & Filename, ReadOnly:=True)
For Each Sht In wb.Sheets
Set ShtDest = ThisWorkbook.Sheets.Add(After:=Sheets(1))
Sht.Cells.Copy
ShtDest.Name = Left(wb.Name, 6)
ShtDest.Cells.PasteSpecial xlValues
Next Sht
wb.Close
Filename = Dir()
Loop
Application.ScreenUpdating = True
Application.DisplayAlerts = True
End Sub
I think I need to add some sort of if statement to check if the name of the workbook that is being opened is the same as each of the individual worksheet names in the master workbook. Perhaps I need a second for each loop to check each of the worksheets in the master workbook? Then for each of the worksheets in the master workbook, find the last populated row and append the data, one row below that.
You can check the name of the workbook worksheets, and paste your values in there. Find below some unchecked and undebugged sample code:
Dim ShtDest As Worksheet
Dim wsName As String
wsName = 'yourWorkSheetNameToFind'
Set ShtDest = wb.Sheets(wsName)
ShtDest.Cells.PasteSpecial xlValues
Even add an ifExists checker:
Function WorksheetExists(shtName As String, Optional wb As Workbook) As Boolean
Dim sht As Worksheet
If wb Is Nothing Then Set wb = ThisWorkbook
On Error Resume Next
Set sht = wb.Sheets(shtName)
On Error GoTo 0
WorksheetExists = Not sht Is Nothing
End Function
So, with the checker:
Dim ShtDest As Worksheet
Dim wsName As String
wsName = 'yourWorkSheetNameToFind'
Set ShtDest = wb.Sheets(wsName)
if WorksheetExists(wsName, wb)
ShtDest.Cells.PasteSpecial xlValues
I have 3 workbooks
source workbook
target workbook
reference workbook - (Containing the macro which visible across all workbooks)
Is it possible to change switch between Active workbook ( target workbook) and ( source workbook which was active workbook).
Activate doesn't seem to help me, I do not if this is a bug or what it is. I have stopped in this step for quite sometime now.
This workbook function takes me back to reference workbook.
Hope my question is clear. Appreciate your help.
' My code is in a test macroworkbook
' I am having a workbook opened 1.xlsx
' Opening a workbook countrypricelist.xls
'running the code from
Dim sourcewb As Workbook
Dim targetWorkbook As Workbook
Dim filter As String
Dim filter2 As String
Dim rw As Long
Dim x As Range
Dim y As Range
Set sourcewb = ActiveWorkbook
Set x = sourcewb.Worksheets(1).Range("A:F")
Dim sourceSheet As Worksheet
Set sourceSheet = sourcewb.Worksheets(1)
MsgBox sourceSheet.Name
x.Select
MsgBox sourceSheet.Name
x.Select
MsgBox sourcewb.Name ' This gives me sourceworkbook name.
filter = "(*.xls),*.xls"
Caption = "Please Select an input file "
Application.ScreenUpdating = False
Filename = Application.GetOpenFilename(filter, , Caption)
Set targetWorkbook = Application.Workbooks.Open(Filename)
Set y = targetWorkbook.Worksheets(1).Range("A:F")
y.Select
Dim targetSheet As Worksheet
Set targetSheet = targetWorkbook.Worksheets(1)
MsgBox targetSheet.Name
Set targetWorkbook = ActiveWorkbook
MsgBox targetWorkbook.Name 'This gives me target workbook name
y.Select
sourcewb.Activate
MsgBox sourcewb.Name ' Source workbook becomes same as targeworkbook.
x.Select
MsgBox sourcewb.Name & " This is the source workbook "
MsgBox targetWorkbook.Name & " This is the target workbook "
With sourcewb.Worksheets(1)
For rw = 2 To Cells(Rows.Count, 1).End(xlUp).Row
Cells(rw, 3) = Application.VLookup(Cells(rw, 2).Value2, x, 3, False)
Cells(rw, 4) = Application.VLookup(Cells(rw, 2).Value2, x, 4, False)
Cells(rw, 5) = Application.VLookup(Cells(rw, 2).Value2, x, 5, False)
Next rw
End With
MsgBox "All required columns from source mapped to target file "
MsgBox "Trying to map from target to source "
Set sourcewb = ActiveWorkbook
MsgBox ActiveWorkbook.Name
Application.ScreenUpdating = False
So If I change the line sourcewb = Thisworkbook my reference is changed to source code to workbook which is not my desired workbook as it contains many other macros for other activities. Hope this is code is fine.
The Excel Workbook Object allows you to programatically open, edit and close any workbook, not just the currently 'Activated' one.
Example:
Dim wb as Excel.Workbook, otherwb as Excel.Workbook
Dim ws as Excel.Worksheet, otherws as Excel.Worksheet
Set wb = Workbooks.Open "somefile.xlsx"
Set otherwb = Workbooks.Open "otherfile.xlsx"
Set ws = wb.Sheets(1)
Set otherws = otherwb.Sheets(1)
' do stuff
ws.Cells(1,1) = otherws.Cells(1,1)
'save changes
wb.Save
I found this great Macro that copies each of my rows in my data frame separately into a new sheet, but keeps the first row with the column names as well:
Sub abc_01()
Dim WS As Worksheet, newWS As Worksheet
Dim X As String
Application.ScreenUpdating = False
Set WS = Sheets("Sheet1")
On Error Resume Next
X = InputBox("number of names 1,2,", , "9")
For i = 1 To X
Set newWS = Worksheets.Add(after:=Worksheets(Worksheets.Count))
WS.Range("A1:G1").Copy Destination:=newWS.Range("A1")
WS.Range(WS.Cells(i + 1, "A"), WS.Cells(i + 1, "G")).Copy
newWS.Range("A2").PasteSpecial xlValues
Next i
On Error GoTo 0
Application.ScreenUpdating = True
End Sub
I tried now to copy it into a new workbook rather than a new sheet, but the new workbook stays empty when I run it. Also, I haven't saved the new workbooks yet as a new filename (ideally a specific cell value if possible?)
Sub abc_02()
Dim thisWB As String
Dim newWB As String
thisWB = ActiveWorkbook.Name
Dim X As String
Application.ScreenUpdating = False
Set WS = Sheets("Sheet1")
On Error Resume Next
X = InputBox("number of names 1,2,", , "9")
For i = 1 To X
Workbooks.Add
ActiveWorkbook.SaveAs supName
newWB = ActiveWorkbook.Name
Windows(thisWB).Activate
Sheets("Sheet1").Select
Range("A1:G1").Copy
Windows(newWB).Activate
Sheets("Sheet1").Select
ActiveSheet.Range("A1").Select
ActiveSheet.Range("A1").Paste
Windows(thisWB).Activate
Sheets("Sheet1").Select
Range(Sheet1.Cells(i + 1, "A"), Sheet1.Cells(i + 1, "G")).Copy
Windows(newWB).Activate
Sheets("Sheet1").Select
Range("A2").PasteSpecial xlValues
Next i
On Error GoTo 0
Application.ScreenUpdating = True
End Sub
I am a VBA noob so any help much appreciated!
In the original code, you have
Dim WS As Worksheet, newWS As Worksheet
Dim X As String
Dim WS as Worksheet and newWS as Worksheet tells Excel "WS and newWS will be worksheets."
Later in the code, these are set respectively, WS as Sheet1 in the active workbook, and newWS as a new worksheet within the active workbook.
Changing
Dim thisWB As String
Dim newWB As String
to
Dim thisWB As Workbook
Dim newWB As Workbook
should fix your issue.
You should be dimming thisWB and newWB as Workbooks, not strings.
Excel will be looking for a string of text instead of Workbooks.
Also - try looking on ExcelForum.com VBA section; I learnt a lot of what I know from there.
Hope that helps
I try to copy a range from a workbook (opened with vba-excel) to another (thisworkbook)
Public wbKA as workbook
Sub A()
Dim oExcel As Excel.Application
KAPath = ThisWorkbook.path & "\Data.xlsx"
Set oExcel = New Excel.Application
Set wbKA = oExcel.Workbooks.Open(KAPath)
...
End Sub
with this code:
Sub Get()
Dim LastRow As Long
With wbKA.Worksheets("Sheet1")
LastRow = .Cells(.Rows.Count, "A").End(xlUp).Row
.Range(.Cells(5, 1), .Cells(LastRow, 1)).Copy
.Range(.Cells(5, 1), .Cells(LastRow, 1)).Copy Destination:=ThisWorkbook.Worksheets("SheetB").Range("A6")
The line .Range(.Cells(5, 1), .Cells(LastRow, 1)).Copy Destination:=ThisWorkbook.Worksheets("SheetB").Range("A6") is highlighted (yellow) by the debugger with the error that the copy method could not be applyed to the range object. The first copy method (just insered by me to check if the error occurs without the Destination part) runs through. I copied the code to another workbook where I apply the copy-destination copy pattern to only one workbook and it is working. Could anyone tell me, why this is not working? The wbKA workbook opens up fine and I can actually perform all I need (Search, Pasting Values into arrays and so on), just the Copy thing doesnt work.
Since you are working from Excel, you do not need to open a new instance. That is creating the copy issues. Try this (Untested)
Sub Sample()
Dim thisWb As Workbook, thatWb As Workbook
Dim thisWs As Worksheet, thatWs As Worksheet
Dim KAPath As String
Dim LastRow As Long
Set thisWb = ThisWorkbook
Set thisWs = thisWb.Sheets("SheetB")
KAPath = ThisWorkbook.Path & "\Data.xlsx"
Set thatWb = Workbooks.Open(KAPath)
Set thatWs = thatWb.Sheets("Sheet1")
With thatWs
LastRow = .Cells(.Rows.Count, "A").End(xlUp).Row
.Range(.Cells(5, 1), .Cells(LastRow, 1)).Copy thisWs.Range("A6")
End With
End Sub
Followup from comments.
You cannot use rng.copy Dest.rng when working with different Excel instances. You will have to first copy it and then paste in the next line. See these examples
This will not work
Sub Sample()
Dim xl As New Excel.Application
Dim wb As Workbook
Dim ws As Worksheet
xl.Visible = True
Set wb = xl.Workbooks.Add
Set ws = wb.Sheets(1)
ws.Range("A1").Value = "Sid"
ws.Range("A1").Copy ThisWorkbook.Sheets(1).Range("A1")
End Sub
This will work
Sub Sample()
Dim xl As New Excel.Application
Dim wb As Workbook
Dim ws As Worksheet
xl.Visible = True
Set wb = xl.Workbooks.Add
Set ws = wb.Sheets(1)
ws.Range("A1").Value = "Sid"
ws.Range("A1").Copy
ThisWorkbook.Sheets(1).Range("A1").PasteSpecial xlValues
End Sub
I have Workbook, source.xlsm, Worksheet "test1" Column A6:A20 that I need to copy to another WorkBook located on my C:... named dest.xlsx, Worksheet "Assets", Column "I". I need to be able to copy the data and be able to add to the column without overwriting the previous data copied. Any help would be a life saver.
Sub Align()
Dim TargetSh As String
TargetSh = "Assets"
For Each WSheet In Application.Worksheets
If WSheet.Name <> TargetSh Then
WSheet.Select
Range("A6:A20").Select
Range(Selection, ActiveCell.SpecialCells(xlLastCell)).Select
Selection.Copy
Sheets(TargetSh).Select
lastRow = Range("I65532").End(xlUp).Row
Cells(lastRow + 1, 1).Select
ActiveSheet.Paste
End If
Next WSheet
End Sub
Is this what you are trying? I have not tested it but I think it should work. Let me know if you get any errors.
Sub Sample_Copy()
Dim wb As Workbook, wbTemp As Workbook
Dim ws As Worksheet, wsTemp As Worksheet
Dim lastRow As Long
Set wb = ThisWorkbook
Set ws = wb.Sheets("test1")
'~~> Change path as applicable
Set wbTemp = Workbooks.Open("C:\dest.xlsx")
Set wsTemp = wbTemp.Sheets("Assets")
lastRow = wsTemp.Range("I" & Rows.Count).End(xlUp).Row + 1
ws.Range("A6:A20").Copy wsTemp.Range("I" & lastRow)
Application.CutCopyMode = False
'~~> Cleanup
wbTemp.Close savechanges:=True
Set wb = Nothing: Set wbTemp = Nothing
Set ws = Nothing: Set wsTemp = Nothing
End Sub
HTH
Sid