I'd like to ask if you could help me with copying some worksheet data from workbook A into my active workbook (workbook B)
I have the following code in the main workbook to copy the data from workbook A
Public Sub Worksheet_Activate()
test
End Sub
Sub test()
Dim Wb1 As Workbook
Dim MainBook As Workbook
'Open All workbooks first:
Set Wb1 = Workbooks.Open("Z:\Folder\WorkbookA.xlsm")
'Set MainBook = Workbooks.Open(Application.ActiveWorkbook.FullName)
Set MainBook = Application.ActiveWorkbook
'Now, copy what you want from wb1:
Wb1.Sheets("Projekte").Cells.Copy
'Now, paste to Main worksheet:
MainBook.Worksheets("Projekte").Range("A1").PasteSpecial xlPasteAll
Application.CutCopyMode = False
'Close Wb's:
Wb1.Close SaveChanges:=False
End Sub
I know, that it opens worksheet A and that it highlights and copys the data.
The script wont paste it into worksheet B (where the script is executed from)
Anybody know what i did wrong?
Kindest regards, and thanks for any help !
You should set the Mainbook (destination) first before the origin (if you're going to use ActiveWorkbook).
'Set MainBook First
Set MainBook = ThisWorkbook
'Open All workbook:
Set Wb1 = Workbooks.Open("Z:\Folder\WorkbookA.xlsm")
Just for clarity, it's just me being OC on this one.
you have to properly reference your workbook and worksheet objects
if you have to paste the whole content of range (including formatting, comments, ...), then you want to code like follows (explanations in comments):
Option Explicit
Sub test()
Dim targetSheet As Worksheet
Set targetSheet = ActiveSheet 'store currently active sheet
Workbooks.Open("Z:\Folder\WorkbookA.xlsm").Sheets("Projekte").UsedRange.Copy Destination:=targetSheet.Range("A1") ' open the wanted workbook and copy its "Projekte" sheet used range to 'targetSheet (i.e.: the sheet in the workbook where it all started) from its cell A1
ActiveWorkbook.Close SaveChanges:=False ' close the currently active workbook (i.e. the just opened one)
End Sub
if you only need to paste values, then this is the way to go (much faster!):
Option Explicit
Sub test()
Dim targetSheet As Worksheet
Set targetSheet = ActiveSheet 'store currently active sheet
With Workbooks.Open("Z:\Folder\WorkbookA.xlsm").Sheets("Projekte").UsedRange ' open the wanted workbook and reference its sheet "Projekte" used range
targetSheet.Range("A1").Resize(.Rows.Count, .Columns.Count).Value = .Value
.Parent.Parent.Close SaveChanges:=False 'close the parent workbook of referenced range (i.e., the newly opened workbook)
End With
End Sub
My recommendation is never to use ActiveWorkbook.
In most cases when people use ActiveWorkbook they actually meant to use ThisWorkbook. The difference is:
ActiveWorkbook is the currently selected one which is "on top of the screen" in exact that moment when your code runs. That can be any workbook the user just clicked on while your code runs. So you never can be 100% sure to get the right workbook.
ThisWorkbook is the actual workbook your code runs at the moment. And this doesn't change ever. So this is a well defined reference and no gamble about which workbook is on top at the moment.
About why your approach did not work
Set Wb1 = Workbooks.Open("Z:\Folder\WorkbookA.xlsm") 'this line makes WorkbookA the active one
Set MainBook = Application.ActiveWorkbook 'this makes MainBook = WorkbookA
Therefore a simple Set MainBook = Application.ThisWorkbook should work here.
Another recommendation
Sheets and Worksheets is not the same. Make sure you never use Sheets when you can use Worksheets.
Sheets contains worksheets and charts
Worksheets contain only worksheets
An example Sheets(1).Range("A1") fails if it is a chart.
Related
I am trying to create a copy of a large macro enabled (xlsm) file in xlsx format.
Sub Button1_Click()
Dim wb As Workbook
Set wb = Workbooks.Open("C:\original.xlsm")
Dim mySheetList() As String
ReDim mySheetList(0 To (ThisWorkbook.Sheets.Count) - 1)
Dim a As Integer
a = 0
For Each ws In ActiveWorkbook.Worksheets
mySheetList(a) = ws.Name
a = a + 1
Next ws
'actually save
Worksheets(mySheetList).Copy
ActiveWorkbook.SaveAs Filename:="ORIGINAL_COPY.xlsx" 'default ext
wb.Close
End Sub
I am getting subscript out of range error at following line:
mySheetList(a) = ws.Name
You are sizing the array with ThisWorkbook.Sheets but the loop use ActiveWorkbook.Worksheets. You need the same reference to avoid issues when multiple workbooks are opened.
You're using 4 different references to workbooks:
wb, ThisWorkbook and ActiveWorkbook are not necessarily the same thing. Furthermore, when you use Worksheets without prefixing it with a workbook reference, you're implicitly referencing the Activeworkbook. And, when you use Worksheets.Copy without any arguments, you're implictly creating a new workbook.
Currently, if ThisWorkbook has fewer sheets than original.xlsm, then your array will not be large enough to accommodate indexes larger than the count of sheets in ThisWorkbook. That is what is causing your out of bounds error.
I've adjusted the code. This will open the XLSM, copy the sheets, save the new XLSX workbook, and close the original XLSM, leaving the new XLSX workbook open.
Sub Button1_Click()
Dim wbOriginal As Workbook
Dim wbOutput As Workbook
Set wbOriginal = Workbooks.Open("C:\original.xlsm")
Dim mySheetList() As String
ReDim mySheetList(0 To (wbOriginal.Sheets.Count) - 1)
Dim a As Integer
a = 0
For Each ws In wbOriginal.Worksheets
mySheetList(a) = ws.Name
a = a + 1
Next ws
'Unfortunately, Worksheets.Copy isn't a function, so it doesn't
'return the workbook that it creates, so we have to execute the
'copy, then find the activeworkbook
Worksheets(mySheetList).Copy
Set wbOutput = ActiveWorkbook
'actually save
wbOutput.SaveAs Filename:="ORIGINAL_COPY.xlsx" 'default ext
wbOriginal.Close
End Sub
Why bother with all that looping?
Sub MM()
Dim sourceWB As Excel.Workbook
Set sourceWB = Workbooks.Open("C:\Original.xlsm")
sourceWB.SaveAs "C:\ORIGINAL_COPY.xlsx", FileFormat:=xlOpenXMLWorkook
sourceWB.Close False '// Optional
End Sub
The .SaveAs() method would be far more effective.
As mentioned in other answers, your issue seems to be with wb, ActiveWorkbook and ThisWorkbook being used interchangeably when they are actually different things.
wb is a workbook object that has been set to "C:\original.xlsm". It will always refer to that workbook unless you close the workbook, empty the object, or assign a new object to it.
ActiveWorkbook refers to the workbook that is currently active in Excel's forefront window. (i.e. The workbook you can see on your screen)
ThisWorkbook refers to the workbook in which the currently executing code belongs to. To quickly explain the difference:
Workbook A is the only workbook open, and has some code in to open another workbook (let's call it Workbook B).
At the moment, Workbook A is the ActiveWorkbook.
The code in workbook A starts running, workbook A is now the ActiveWorkbook and ThisWorkbook (because the running codes resides in this workbook)
The code opens Workbook B, which naturally opens in the forefront of Excel. Now Workbook B is the ActiveWorkbook and Workbook A is still the ThisWorkbook
Hopefully that clears it up a bit for you...
I have an existing workbook that will be used by multiple users (who will name the workbook uniquely - I can set one Workbook Codename if needed though, though don't know how to do this?).
I need to create a macro that opens a new workbook (which presumably I won't know the name of? as it could be 'Book1', 'Book2', 'Book3' etc?), then returns to the original workbook where the macro is stored, and copies several (can do one at a time if needed) sheets (that I DO know the names of these sheets) and pastes them as new sheets into the new workbook that I created at the start. The macro does not need to Save the file (in fact it's preferable that it doesn't as I want the user to save the new workbook wherever is most convenient for the user).
I have attempted to show what the macro would do, showing the obvious problem that I do not know the names of the workbooks I am creating/copying from/pasting into.
Any help, much appreciated!
Sub CopySheetintoNewWorkbook()
'Macro opens new / blank workbook (name unknown?)'
Workbooks.Add
'Macro goes back to original workbook where macro is saved (of which the name is unknown to the macro - i.e., users can and will change it)'
Windows("UnknownWorkbookName-1").Activate
'Macro goes to a sheet which can be named and will be known, so this is no problem'
Sheets("KnownSheet").Select
'Macro creates a copy of the sheet and pastes it as a new sheet within the new, unknown named workbook'
Application.CutCopyMode = False
Sheets("KnownSheet").Copy Before:=Workbooks("UnknownWorkbookName-2").Sheets(1)
End Sub
We want to copy Sheet1 and Sheet2.
This relies on a tiny trick:
Sub qwerty()
Dim wb1 As Workbook, wbNEW As Workbook
Set wb1 = ActiveWorkbook
Sheets("Sheet1").Copy
Set wbNEW = ActiveWorkbook
wb1.Sheets("Sheet2").Copy after:=wbNEW.Sheets(1)
End Sub
When the first .Copy is performed, a new workbook is created and it becomes the ActiveWorkbook ........the rest is easy.
EDIT#1:
If we have a group of sheets to be copied, then we can create an array of sheet names and loop through the array, copying one sheet at a time:
Sub qwerty()
Dim wb1 As Workbook, wbNEW As Workbook
Dim ary() As String, s As String, i As Long
s = "Larry,Moe,Curly"
ary = Split(s, ",")
Set wb1 = ActiveWorkbook
i = 1
For Each a In ary
If i = 1 Then
Sheets(a).Copy
Set wbNEW = ActiveWorkbook
Else
wb1.Sheets(a).Copy after:=wbNEW.Sheets(1)
End If
i = 2
Next a
wbNEW.Activate
End Sub
I am trying to copy a whole sheet from one Excel file to a sheet in another. Following is the code I wrote which doesn't work. Please suggest changes.
Sub copyallwos()
Dim wkbSource As Workbook
Dim wkbDest As Workbook
Dim shttocopy As Worksheet
Dim wbname As String
Set wkbSource = Workbooks.Open("C:\Users\AV\Documents\New folder\SCADA Wos.xlsm")
Set wkbDest = Workbooks("C:\Users\AV\Documents\New folder\MASTER.xlsm")
'perform copy
Set shttocopy = wkbSource.Sheets("tt")
shttocopy.Copy
wkbDest.Sheets("SCADAWOs").Select
ActiveSheet.Paste
End Sub
Try this under 'perform copy
wkbSource.Sheets("tt").Copy After:=wkbDest.Sheets("SCADAWOs")
You can also insert the sheet before your "SCAD..." sheet, just change After:= to Before:=. Also, if you don't necessarily know a sheet name in the destination workbook, you can use After:=Wkbdest.sheets(sheets.count) which will instert it after the last Worksheet.
I've been able to make an exact copy of a worksheet and add it to the workbook with:
Sub Test()
Dim ws1 As Worksheet
Set ws1 = ThisWorkbook.Worksheets("Detailed List")
ws1.Copy ThisWorkbook.Sheets(Sheets.Count)
End Sub
but I'm trying to have the copied worksheet paste over another worksheet. For example, I'm trying to copy the worksheet "Detailed List" and have it paste and overwrite "Testing Sheet", but all I'm able to do with the code above is make another worksheet. Any help would be great.
You nearly had it, and your own solution works...however, in the efforts of completeness...
Sub Test()
Dim ws1 As Worksheet
Dim ws1Copy As Worksheet
Set ws1 = ThisWorkbook.Worksheets("Detailed List")
ws1.Copy ThisWorkbook.Sheets(Sheets.Count) 'we can't set the copied object directly to a varaiable, but it becomes the active sheet by default
Set ws1Copy = ActiveSheet 'assign the newly copied activesheet to a variable
Application.DisplayAlerts = False 'supress warnings, the delete method gives the user a warning
Sheets("Testing Sheet").Delete 'delete the testing sheet
Application.DisplayAlerts = True 'un-supress the warnings
ws1Copy.Name = "Testing Sheet" 'change the name of the copied sheet to the testing sheet.
End Sub
So I ended up doing this:
Worksheets("Detailed List").Range("A7").CurrentRegion.Copy
Worksheets("Detailed Copy").Range("A7").PasteSpecial
I first just copied the Detailed List before I started running the macro. Then I highlighted all the data points and titles, and overwrite the Copy. I needed to do this because I am making a macro that whenever someone changes a cell in the "Detailed List", I need to display the Old Value that used to be in the cell, so by having essentially two copies of the List, I can first make the comparisons, and then just copy the list over and over, so it automatically updates itself to any changes that have been made.
I have come across some code to copy a range to a new workbook, but I'm not sure why it works.
Worksheets("Short Form").Copy
Set wb = ActiveWorkbook
How does this copy the worksheet 'Short Form' to a new workbook when all that the code says is assign the active workbook to the reference 'wb'? It doesn't even employ the .add method. Right now I want to paste values only to this new workbook, but not quite sure how to do so because I don't understand this block of code.
Try this - as the following manual steps are the same as your code snippet:
1.Open a blank workbook
2.Press record macro
3.Right click the Sheet1 workbook tab
4.Select "Move or Copy"
5.In the "To book" combo select (new book)
6.Check the "Create a copy" box so that the window now looks like this:
7.Stop the recorder
8.Go and find your recorded code ...and voila....mine looks like this
Option Explicit
Sub Macro1()
'
' Macro1 Macro
'
'
Sheets("Sheet1").Select
Sheets("Sheet1").Copy
End Sub
Your code is the same as what these manual steps describe.
You must have a line Dim wb as workbook somewhere or it would not run.
This line Set wb = ActiveWorkbook will then make the object wb equal to the new workbook that you have copied into, as it is active, so you can do further operations on it. You can easily switch the workbook that wb is pointed at:
Sub Macro1()
Dim wb As Workbook
ThisWorkbook.Sheets("Sheet1").Copy
Set wb = ActiveWorkbook
MsgBox wb.Name
ThisWorkbook.Activate
Set wb = ActiveWorkbook
MsgBox wb.Name
End Sub
BUT
In my production code I generally never use Set x To ActiveWorkbook I always name the workbook and then use Set x To Workbooks("DefiniteName")
WITHOUT USING CLIPBOARD
If you want to avoid using the clip board then the following example shows how to move values-only data without using paste:
Sub WithoutPastespecial()
Dim firstRange As Range
Set firstRange = ThisWorkbook.Worksheets("Short Form").Range("S4:S2000") 'can change S4:S2000 to the range you want to copy
Dim newBk As Workbook
Dim secondRange As Range
Set newBk = Workbooks.Add
Set secondRange = newBk.Worksheets("Sheet1").Range("A1")
With firstRange
Set secondRange = secondRange.Resize(.Rows.Count, .Columns.Count)
End With
secondRange.Value = firstRange.Value
End Sub
Note this is not copying a Range rather the entire worskheet :)
If you use the method:
Worksheets("Short Form").Cells.Copy
Then you will copy only the cells, not the entire worksheet, and this method will NOT create a new workbook. You can tell it to add a workbook when necessary.
Here is an example:
Option Explicit
Sub CopyNew()
Dim wbNew As Workbook
Dim wb As Workbook
Set wb = ThisWorkbook 'It is a good idea to explicitly control workbooks using either a defined variable like "wb" or the "ThisWorkbook" object, instead of using "ActiveWorkbook" or referring to files by name.
Application.CutCopyMode = False
wb.Sheets("Short Form").Cells.Copy
'Add a new workbook for the values:
Set wbNew = Workbooks.Add
wbNew.Sheets(1).Cells.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
End Sub