I've seen quite a few examples for making a full copy of a worksheet but none of them are working for me. In my case the sheet has to go into a new workbook. In my actual code wb is defined global and the workbook is created in another sub that called this one.
Dim wb As Workbook
Set wb = Workbooks.Add()
Dim newtab as Worksheet
With ActiveWorkbook
.Sheets("Sample Attendance").Copy After:=wb.Sheets(.Sheets.Count)
Set newtab = wb.Sheets(wb.Sheets.Count - 1)
End With
didn't work.
Likewise
ActiveWorkbook.Sheets("Sample Attendance").Copy After:=wb.Sheets(1)
Set newtab = wb.Sheets("Sample Attendance")
newtab.Name = tabname
both methods return after the Copy statement.
I've been moderately successful with this:
Set newtab = wb.Worksheets.Add
newtab.Name = tabname
Set Attendance = ThisWorkbook.Sheets("Sample Attendance")
Attendance.Range("A:BB").Copy Destination:=newtab.Cells(1, 1)
which works. But then I have to copy all of the PageSetup across which is giving me fits and takes forever.
I see two problems with your 1st piece of code...
You are using Activeworkbook. When you add a new workbook, the new workbook becomes your active workbook :)
The second problem is the DOT before .Sheets.Count in wb.Sheets(.Sheets.Count). why pick the count from the workbook you are copying?
Try this
Sub Sample()
Dim thiswb As Workbook, wb As Workbook
Dim newtab As Worksheet
Set thiswb = ThisWorkbook
Set wb = Workbooks.Add()
With thiswb
.Sheets("Sample Attendance").Copy After:=wb.Sheets(wb.Sheets.Count)
Set newtab = wb.Sheets(wb.Sheets.Count - 1)
End With
End Sub
Give this a shot:
Sub SheetCopier()
Dim OriginalWB As Workbook
Dim NewWB As Workbook
Set OriginalWB = ActiveWorkbook
Workbooks.Add
Set NewWB = ActiveWorkbook
OriginalWB.Sheets("qwerty").Copy Before:=NewWB.Sheets(1)
End Sub
Related
I have a number of scripts that are in a module in my Personal.xlsb file. It's kept hidden, but in this script, the idea is that you run it from within a different workbook each time. It opens a separate workbook (source.xlsx), copies a range from it, pastes into the original workbook, and then closes source.xlsx.
When it comes to the "ThisWorkbook.ActiveSheet.Paste" part, it's pasting it into the Personal.xlsb workbook instead of the target workbook that is actually open and visible. How can I make sure it's being pasted in the right workbook? The workbook's filename will always be different, so I can't specify a path or anything like that.
Sub CopyData()
Application.DisplayAlerts = False
Dim wbSource As Workbook
Set wbSource = Workbooks.Open(Filename:="source.xlsx", UpdateLinks:=3)
wbSource.Sheets(1).Range("A1:X105").Copy
ThisWorkbook.ActiveSheet.Paste
wbSource.Close
Application.DisplayAlerts = True
Call CopyCFormat
End Sub
Don't use ThisWorkbook in most cases, as it references the workbook that the macro is stored in (in this case, personal.xlsb).
Instead, you can use ActiveWorkbook to refer to whichever workbook has focus at the time the macro is run. You can also assign ActiveWorkbook to a variable for easier reference.
Sub CopyData()
Application.DisplayAlerts = False
Dim wbSource As Workbook
Dim wbTarget as Workbook
Set wbTarget = ActiveWorkbook
Set wbSource = Workbooks.Open(Filename:="source.xlsx", UpdateLinks:=3)
wbSource.Sheets(1).Range("A1:X105").Copy
wbTarget.ActiveSheet.Paste
wbSource.Close
Application.DisplayAlerts = True
Call CopyCFormat
End Sub
You could also reference the active sheet without specifying which workbook it's in, as:
Dim wbSource As Workbook
Dim shtTarget as Worksheet
Set shtTarget = ActiveSheet
Set wbSource = Workbooks.Open(Filename:="source.xlsx", UpdateLinks:=3)
wbSource.Sheets(1).Range("A1:X105").Copy
shtTarget.ActiveSheet.Paste
Luck!
If I understand it, you should just add another workbook variable.
Sub CopyData()
Dim mainWB As Workbook
Dim mainWS As Worksheet
Set mainWB = ActiveWorkbook
Set mainWS = mainWB.Sheets(1) ' Change this to whatever you need it to be
Application.DisplayAlerts = False
Dim wbSource As Workbook
Set wbSource = Workbooks.Open(Filename:="source.xlsx", UpdateLinks:=3)
wbSource.Sheets(1).Range("A1:X105").Copy
mainWS.Paste
wbSource.Close
Application.DisplayAlerts = True
Call CopyCFormat
End Sub
I'm working on a macro that will move a sheet from a selected Excel sheet into a document with a macro already loaded.
I'm having issues with actually getting the sheet to move over, I keep receiving a subscript out of range error and I'm unsure of why
I've perused stackoverflow and a few other resources so far. I've attempted using .sheets / workbook(workbookname).worksheets(1).copy ...so on and so forth.
Sub runEXCEL()
dim wb1 as workbook, wb2 as workbook
dim fd as filedialog
dim shtpath as string
dim ws as worksheet
Set fd = Application.FileDialog(msoFileDialogFilePicker)
If fd.Show = True Then
If fd.SelectedItems(1) <> vbNullString Then
shtpath = fd.SelectedItems(1)
End If
Else
End
End If
set wb1 = workbooks.open("c:\users\username\documents\yestbook.xlsm", true, false
set wb2 = workbooks.open(shtpath)
set ws = wb2.worksheets(1)
ws.name = "testname"
ws.worksheets(1).copy after:=wb1.sheets(1)
'xl.Application.Run "yestbook.xlsm!findCellAddress"
End Sub
Ideally I would like to copy a sheet from a selected workbook into my predefined workbook.
Subscript out of range occurs because "yestbook.xlsm" does not exist in the global Workbooks collection, which is in this case limited to the active instance of Excel (i.e., the instance from which this code is executed). You've opened two workbooks, each in a new and separate instance of Excel, which presents further problems, because you can't actually Copy worksheets between instances like this.
This should work, unless there are some extraordinary reasons why each file must open in its own instance:
Dim wb1 As Workbook, wb2 as Workbook
Dim fd As FileDialog
Dim shtpath As String
Dim ws As Worksheet
Set fd = Application.FileDialog(msoFileDialogFilePicker)
If fd.Show = True Then
If fd.SelectedItems(1) <> vbNullString Then
shtpath = fd.SelectedItems(1)
End If
Else
End
End If
Set wb1 = Workbooks.Open("C:\Users\username\Desktop\yestbook.xlsm", True, False)
Set wb2 = Workbooks.Open(shtpath)
Set ws = wb2.Worksheets(1)
ws.Name = "testname"
ws.Copy after:=wb1.Sheets(1)
It is not necessary to create additional Excel processes (actually, this might be cause of the problem). You should also use workbook and worksheets variables for all sheet access, and avoid unqualified access like Sheets("testname").
Try something along the lines of:
Dim wb as workbook, ws as worksheet, wb2 as workbook, ws2 as worksheet
Set wb = Workbooks.Open(mysheetpath1)
Set ws=wb.Worksheets(1)
set wb2=Workbooks.Open(mysheetpath2)
set ws2=wb2.Worksheets(1)
ws2.Copy after:=ws
Second to last line - you have
ws.worksheets(1).copy after:=wb1.sheets(1)
This should be
wb.worksheets(1).copy after:=wb1.sheets(1)
it's a typo on the second char
Workbooks.Open "C:\abc.xlsx"
Workbooks("abc").Worksheets("Sheet1").Range("A1:B7").Clear
In the above code I am opening the workbook using Workbooks.Open in first line. In the second line I am accessing the opened workbook using the workbook name.
How can I access the opened workbook without the filename in second line?
(I want to create a function and I don't want to pass both the file paths and filenames separately)
You need to use references and reference the workbook and the sheet for example:
Option Explicit
Sub OpenWorkbook()
Dim wb As Workbook, ws As Worksheet
Set wb = Workbooks.Open("C:\abc.xlsx", UpdateLinks:=False, ReadOnly:=True)
Set ws = wb.Sheets("Sheet1")
ws.Range("A1:B7").ClearContents
End Sub
Note that the parameters on the openworkbook such as Updatelinksand ReadOnly can be modified to True or Falseas you need to.
Create an object of type Excel.Workbook and open the workbook into that.
Like so
Dim w as Excel.Workbook
set w= Workbooks.Open ("C:\abc.xlsx")
and then you can say
w.worksheets.add.....
etc
You can shorten your code:
Option Explicit
Sub OpenWb()
Dim ws As Worksheet
Set ws = Workbooks.Open("C:\abc.xlsx").Worksheets("Sheet1")
With ws '<- Use With Statement to avoid sheet repetition
.Range("A1:B7").ClearContents
End With
End Sub
You can try this
Option Explicit
Sub TEST()
Dim WB As Workbook
Set WB = Workbooks.Open(Filename:="C:\abc.xlsx")
For Each WB In Workbooks
If WB.Name = "abc.xlsx" Then
WB.Worksheets(Sheet1).Range("A1:B7").ClearContents
Exit Sub
End If
Next
End Sub
I have to 2 Excel workbooks to work with: Book1october & Book2. Book1october18 is an import file, meaning that it changes monthly, along with the name (next month it will be Book1november18). I have to copy some data from Book1october to Book2 automatically through VBA code.
This is the code that I've written:
Windows("Book1october18").Activate
Sheets("Sheet1").Activate
Range("B2:AQ5").Select
Selection.Copy
Windows("Book2").Activate
Sheets("Sheet1").Activate
Range("R2:BG5").Select
ActiveSheet.Paste
My problem is that I don't know how to write the code in order to make the actions that I want whenever the month's name changes and also the year. (I have to make it for all the months and 2019)
You can automatically update your workbook name using the Date() function and Format()
Dim sWbName As String
sWbName = "Book1" & LCase(Format(Date, "mmmmyy"))
Debug.Print sWbName
'Prints Book1october18
The name/path of the workbook doesn't need to matter. Use K.Davis's code to come up with a filename, or prompt the user for a path/file to open - get that string into some sourceBookPath variable, then have the macro open the workbook. Now you can hold a reference to that Workbook object:
Dim sourceBook As Workbook
Set sourceBook = Application.Workbooks.Open(sourceBookPath)
Now, the worksheet.
Dim sourceSheet As Worksheet
If the sheet is always going to be named "Sheet1", then you can do this:
Set sourceSheet = sourceBook.Worksheets("Sheet1")
Or, if the sheet is always going to be the first sheet in the book (regardless of its name), you can do this:
Set sourceSheet = sourceBook.Worksheets(1)
Once you have a Worksheet object, you can get the Range you need - but first you need your target. Again if "book2" is opened by the macro, things are much simpler:
Dim targetBook As Workbook
Set targetBook = Application.Workbooks.Open(targetBookPath)
Or is it created by the macro?
Set targetBook = Application.Workbooks.Add
Anyway, we want the first sheet:
Dim targetSheet As Worksheet
Set targetSheet = targetBook.Worksheets(1)
And now we can copy from the source, and paste to the target:
sourceSheet.Range("B2:AQ5").Copy targetSheet.Range("R2:BG5")
And not once did we ever need to .Select or .Activate anything, and we never needed to care for any Window.
Replace:
Windows("Book1october18").Activate
with:
s = LCase(Format(Now, "mmmm")) & Right(Year(Now), 2)
Windows(s).Activate
Try this.
This is a recognition of the next month's document, assuming you have opened two documents.
Sub test()
Dim Wb1 As Workbook, wb2 As Workbook
Dim Wb As Workbook
For Each Wb In Workbooks
If InStr(Wb.Name, "Book1") Then
Set Wb1 = Wb
ElseIf InStr(Wb.Name, "Book2") Then
Set wb2 = Wb
End If
Next Wb
Wb1.Sheets("Sheet1").Range("B2:AQ5").Copy wb2.Sheets("Sheet1").Range("r2")
End Sub
I have an open workbook from it I want to fetch data in another workbook.
My code is:
Dim wbsource as workbook
Dim wssource as worksheet
Dim wbtarget as workbook
Dim wstarget as worksheet
set wbsource = workbooks("D:/test.xlsx")
Even though my source workbook name and address is correct it's giving subscript out of range error.
If I close my source workbook and use
Set wbsource = workbooks.open ("D:/test.xlsx")
it works fine.
Try matching the name in the Set command to the caption name:
Sub SetupWorkbookObject()
Dim wb As Workbook
Set wb = Workbooks("sample.xlsm")
MsgBox wb.Name
End Sub
Note:
Neither the Set command nor the window caption have the full filespec, only the filename.